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
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
//! Database interface.

use crate::reading::Reading;
use crate::value::Value;
use crate::Result;
use chashmap::CHashMap;
use chrono::prelude::*;
use rusqlite::types::*;
use rusqlite::{Connection, Row, ToSql, NO_PARAMS};
use std::path::Path;

const SCHEMA: &str = "
    -- Stores all sensor readings.
    CREATE TABLE IF NOT EXISTS readings (
        sensor TEXT NOT NULL,
        ts INTEGER NOT NULL,
        value TEXT NOT NULL
    );
    -- Descending index on `ts` is needed to speed up the select latest queries.
    CREATE UNIQUE INDEX IF NOT EXISTS readings_sensor_ts ON readings (sensor, ts DESC);

    -- Tables for key-value store.
    CREATE TABLE IF NOT EXISTS integers (
        `key` TEXT NOT NULL PRIMARY KEY,
        value INTEGER,
        expires INTEGER NOT NULL
    );
    CREATE TABLE IF NOT EXISTS reals (
        `key` TEXT NOT NULL PRIMARY KEY,
        value REAL,
        expires INTEGER NOT NULL
    );
    CREATE TABLE IF NOT EXISTS texts (
        `key` TEXT NOT NULL PRIMARY KEY,
        value TEXT,
        expires INTEGER NOT NULL
    );
    CREATE TABLE IF NOT EXISTS blobs (
        `key` TEXT NOT NULL PRIMARY KEY,
        value BLOB,
        expires INTEGER NOT NULL
    );
";

/// A database connection.
pub struct Db {
    /// Wrapped SQLite connection.
    connection: Connection,

    /// Readings cache. Stores the latest reading for each sensor.
    _cache: CHashMap<String, Reading>,
}

impl Db {
    /// Create a new database connection.
    pub fn new<P: AsRef<Path>>(path: P) -> Result<Db> {
        let connection = Connection::open(path)?;
        connection.execute_batch(SCHEMA)?;
        Ok(Db {
            connection,
            _cache: CHashMap::new(),
        })
    }
}

/// Serializes value to JSON.
impl ToSql for Value {
    fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
        match serde_json::to_string(&self) {
            Ok(string) => Ok(ToSqlOutput::Owned(rusqlite::types::Value::Text(string))),
            Err(error) => Err(rusqlite::Error::ToSqlConversionFailure(Box::new(error))),
        }
    }
}

/// De-serializes value from JSON.
impl FromSql for Value {
    fn column_result(value: ValueRef) -> FromSqlResult<Self> {
        match serde_json::from_str(value.as_str()?) {
            Ok(value) => Ok(value),
            Err(error) => Err(FromSqlError::Other(Box::new(error))),
        }
    }
}

/// Initializes reading from database row.
impl From<&Row<'_>> for Reading {
    fn from(row: &Row<'_>) -> Self {
        Reading {
            sensor: row.get_unwrap("sensor"),
            timestamp: Local.timestamp_millis(row.get_unwrap("ts")),
            value: row.get_unwrap("value"),
        }
    }
}

/// Readings persistence.
impl Db {
    /// Insert reading into database.
    pub fn insert_reading(&self, reading: &Reading) -> Result<()> {
        self.connection
            .prepare_cached("INSERT OR REPLACE INTO readings (sensor, ts, value) VALUES (?1, ?2, ?3)")?
            .execute(&[
                &reading.sensor as &dyn ToSql,
                &reading.timestamp.timestamp_millis(),
                &reading.value,
            ])?;
        Ok(())
    }

    /// Select latest reading for each sensor.
    pub fn select_latest_readings(&self) -> Result<Vec<Reading>> {
        self.connection
            .prepare_cached("SELECT sensor, MAX(ts) as ts, value FROM readings GROUP BY sensor")?
            .query_map(NO_PARAMS, |row| Ok(Reading::from(row)))?
            .map(|result| result.map_err(|e| e.into()))
            .collect()
    }

    /// Select database size in bytes.
    pub fn select_size(&self) -> Result<u64> {
        self.connection
            .prepare_cached("SELECT page_count * page_size as size FROM pragma_page_count(), pragma_page_size()")?
            .query_row(NO_PARAMS, |row| row.get::<_, i64>(0))
            .map(|v| v as u64)
            .map_err(|e| e.into())
    }

    /// Select the very last sensor reading.
    pub fn select_last_reading(&self, sensor: &str) -> Result<Option<Reading>> {
        Ok(self
            .connection
            .prepare_cached("SELECT sensor, ts, value FROM readings WHERE sensor = ?1 ORDER BY ts DESC LIMIT 1")?
            .query_row(&[&sensor as &dyn ToSql], |row| Ok(Some(Reading::from(row))))
            .unwrap_or(None))
    }

    /// Select the latest sensor readings within the given time interval.
    pub fn select_readings(&self, sensor: &str, since: &DateTime<Local>) -> Result<Vec<Reading>> {
        Ok(self
            .connection
            .prepare_cached("SELECT sensor, ts, value FROM readings WHERE sensor = ?1 AND ts >= ?2 ORDER BY ts")?
            .query_map(&[&sensor as &dyn ToSql, &since.timestamp_millis()], |row| {
                Ok(Reading::from(row))
            })?
            .map(|result| result.unwrap())
            .collect())
    }
}

/// Key-value store.
impl Db {
    /// Get an item from the key-value store.
    pub fn get<K, V>(&self, key: K) -> Result<Option<V>>
    where
        K: AsRef<str>,
        V: SqliteTypeName + FromSql,
    {
        Ok(self
            .connection
            .prepare_cached(&format!(
                "SELECT value FROM {}s WHERE `key` = ?1 AND expires > ?2",
                V::name()
            ))?
            .query_row(
                &[&key.as_ref() as &dyn ToSql, &Local::now().timestamp_millis()],
                |row| Ok(Some(row.get_unwrap::<_, V>("value"))),
            )
            .unwrap_or(None))
    }

    /// Set item in generic key-value store.
    pub fn set<K, V, E>(&self, key: K, value: V, expires_at: E) -> Result<()>
    where
        K: AsRef<str>,
        V: SqliteTypeName + ToSql,
        E: Into<DateTime<Local>>,
    {
        self.connection
            .prepare_cached(&format!(
                "INSERT OR REPLACE INTO {}s (`key`, value, expires) VALUES (?1, ?2, ?3)",
                V::name()
            ))?
            .execute(&[
                &key.as_ref() as &dyn ToSql,
                &value,
                &expires_at.into().timestamp_millis(),
            ])?;
        Ok(())
    }
}

/// Trait which returns SQLite type name of the implementing type.
pub trait SqliteTypeName {
    fn name() -> &'static str;
}

impl SqliteTypeName for i32 {
    fn name() -> &'static str {
        "integer"
    }
}

impl SqliteTypeName for f64 {
    fn name() -> &'static str {
        "real"
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::Duration;

    type Result = crate::Result<()>;

    #[test]
    fn set_and_get() -> Result {
        let db = Db::new(":memory:")?;
        db.set("hello", 42, Local::now() + Duration::days(1))?;
        assert_eq!(db.get::<_, i32>("hello").unwrap(), Some(42));
        Ok(())
    }

    #[test]
    fn get_missing_returns_none() -> Result {
        assert_eq!(Db::new(":memory:")?.get::<_, i32>("missing")?, None);
        Ok(())
    }

    #[test]
    fn expired_returns_none() -> Result {
        let db = Db::new(":memory:")?;
        db.set("hello", 42, Local::now())?;
        assert_eq!(db.get::<_, i32>("hello")?, None);
        Ok(())
    }

    #[test]
    fn cannot_get_different_type_value() -> Result {
        let db = Db::new(":memory:")?;
        db.set("hello", 42, Local::now() + Duration::days(1))?;
        assert_eq!(db.get::<_, f64>("hello")?, None);
        Ok(())
    }

    #[test]
    fn select_last_reading() -> Result {
        let reading = Reading {
            sensor: "test".into(),
            value: Value::Counter(42),
            timestamp: Local.timestamp_millis(1_566_424_128_000),
        };
        let db = Db::new(":memory:")?;
        db.insert_reading(&reading)?;
        assert_eq!(db.select_last_reading("test")?, Some(reading));
        Ok(())
    }
}