2023-05-17 04:46:48 +00:00
|
|
|
use std::path::Path;
|
|
|
|
|
2021-07-10 16:07:37 +00:00
|
|
|
use ::diesel::{query_dsl::*, ExpressionMethods};
|
2023-05-17 04:46:48 +00:00
|
|
|
use anyhow::anyhow;
|
2021-07-10 16:07:37 +00:00
|
|
|
use diesel::{Connection, SqliteConnection};
|
|
|
|
use lazy_static::lazy_static;
|
2023-05-17 04:46:48 +00:00
|
|
|
use parking_lot::RwLock;
|
|
|
|
use serde::de::DeserializeOwned;
|
|
|
|
use serde::Serialize;
|
|
|
|
|
|
|
|
use crate::kv::schema::{kv_table, kv_table::dsl, KV_SQL};
|
|
|
|
use crate::sqlite::{DBConnection, Database, PoolConfig};
|
2022-01-28 02:56:55 +00:00
|
|
|
|
2021-07-10 16:07:37 +00:00
|
|
|
const DB_NAME: &str = "kv.db";
|
|
|
|
lazy_static! {
|
2023-02-13 01:29:49 +00:00
|
|
|
static ref KV_HOLDER: RwLock<KV> = RwLock::new(KV::new());
|
2021-07-10 16:07:37 +00:00
|
|
|
}
|
|
|
|
|
2023-05-17 04:46:48 +00:00
|
|
|
/// [KV] uses a sqlite database to store key value pairs.
|
|
|
|
/// Most of the time, it used to storage AppFlowy configuration.
|
2021-09-03 04:44:48 +00:00
|
|
|
pub struct KV {
|
2023-02-13 01:29:49 +00:00
|
|
|
database: Option<Database>,
|
2021-07-10 16:07:37 +00:00
|
|
|
}
|
|
|
|
|
2021-09-03 04:44:48 +00:00
|
|
|
impl KV {
|
2023-02-13 01:29:49 +00:00
|
|
|
fn new() -> Self {
|
|
|
|
KV { database: None }
|
|
|
|
}
|
|
|
|
|
|
|
|
#[tracing::instrument(level = "trace", err)]
|
2023-05-17 04:46:48 +00:00
|
|
|
pub fn init(root: &str) -> Result<(), anyhow::Error> {
|
2023-02-13 01:29:49 +00:00
|
|
|
if !Path::new(root).exists() {
|
2023-05-17 04:46:48 +00:00
|
|
|
return Err(anyhow!("Init KV failed. {} not exists", root));
|
2021-07-10 16:07:37 +00:00
|
|
|
}
|
|
|
|
|
2023-02-13 01:29:49 +00:00
|
|
|
let pool_config = PoolConfig::default();
|
|
|
|
let database = Database::new(root, DB_NAME, pool_config).unwrap();
|
|
|
|
let conn = database.get_connection().unwrap();
|
|
|
|
SqliteConnection::execute(&*conn, KV_SQL).unwrap();
|
2021-07-11 07:33:19 +00:00
|
|
|
|
2023-02-13 01:29:49 +00:00
|
|
|
tracing::trace!("Init kv with path: {}", root);
|
2023-05-17 04:46:48 +00:00
|
|
|
KV_HOLDER.write().database = Some(database);
|
2021-07-11 07:33:19 +00:00
|
|
|
|
2023-02-13 01:29:49 +00:00
|
|
|
Ok(())
|
|
|
|
}
|
2022-01-28 02:56:55 +00:00
|
|
|
|
2023-05-17 04:46:48 +00:00
|
|
|
/// Set a string value of a key
|
|
|
|
pub fn set_str<T: ToString>(key: &str, value: T) {
|
|
|
|
let _ = Self::set_key_value(key, Some(value.to_string()));
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Set a bool value of a key
|
|
|
|
pub fn set_bool(key: &str, value: bool) -> Result<(), anyhow::Error> {
|
|
|
|
Self::set_key_value(key, Some(value.to_string()))
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Set a object that implements [Serialize] trait of a key
|
|
|
|
pub fn set_object<T: Serialize>(key: &str, value: T) -> Result<(), anyhow::Error> {
|
|
|
|
let value = serde_json::to_string(&value)?;
|
|
|
|
Self::set_key_value(key, Some(value))?;
|
|
|
|
Ok(())
|
2023-02-13 01:29:49 +00:00
|
|
|
}
|
2022-01-28 02:56:55 +00:00
|
|
|
|
2023-05-17 04:46:48 +00:00
|
|
|
/// Set a i64 value of a key
|
|
|
|
pub fn set_i64(key: &str, value: i64) -> Result<(), anyhow::Error> {
|
|
|
|
Self::set_key_value(key, Some(value.to_string()))
|
|
|
|
}
|
2022-01-28 02:56:55 +00:00
|
|
|
|
2023-05-17 04:46:48 +00:00
|
|
|
/// Get a string value of a key
|
|
|
|
pub fn get_str(key: &str) -> Option<String> {
|
|
|
|
Self::get_key_value(key).and_then(|kv| kv.value)
|
|
|
|
}
|
2022-01-28 02:56:55 +00:00
|
|
|
|
2023-05-17 04:46:48 +00:00
|
|
|
/// Get a bool value of a key
|
|
|
|
pub fn get_bool(key: &str) -> bool {
|
|
|
|
Self::get_key_value(key)
|
|
|
|
.and_then(|kv| kv.value)
|
|
|
|
.and_then(|v| v.parse::<bool>().ok())
|
|
|
|
.unwrap_or(false)
|
|
|
|
}
|
2022-01-28 02:56:55 +00:00
|
|
|
|
2023-05-17 04:46:48 +00:00
|
|
|
/// Get a i64 value of a key
|
|
|
|
pub fn get_i64(key: &str) -> Option<i64> {
|
|
|
|
Self::get_key_value(key)
|
|
|
|
.and_then(|kv| kv.value)
|
|
|
|
.and_then(|v| v.parse::<i64>().ok())
|
|
|
|
}
|
2022-01-28 02:56:55 +00:00
|
|
|
|
2023-05-17 04:46:48 +00:00
|
|
|
/// Get a object that implements [DeserializeOwned] trait of a key
|
|
|
|
pub fn get_object<T: DeserializeOwned>(key: &str) -> Option<T> {
|
|
|
|
Self::get_str(key).and_then(|v| serde_json::from_str(&v).ok())
|
|
|
|
}
|
2022-01-28 02:56:55 +00:00
|
|
|
|
2023-05-17 04:46:48 +00:00
|
|
|
#[allow(dead_code)]
|
|
|
|
pub fn remove(key: &str) {
|
|
|
|
if let Ok(conn) = get_connection() {
|
|
|
|
let sql = dsl::kv_table.filter(kv_table::key.eq(key));
|
|
|
|
let _ = diesel::delete(sql).execute(&*conn);
|
|
|
|
}
|
|
|
|
}
|
2022-01-28 02:56:55 +00:00
|
|
|
|
2023-05-17 04:46:48 +00:00
|
|
|
fn set_key_value(key: &str, value: Option<String>) -> Result<(), anyhow::Error> {
|
|
|
|
let conn = get_connection()?;
|
|
|
|
diesel::replace_into(kv_table::table)
|
|
|
|
.values(KeyValue {
|
|
|
|
key: key.to_string(),
|
|
|
|
value,
|
|
|
|
})
|
|
|
|
.execute(&*conn)?;
|
|
|
|
Ok(())
|
|
|
|
}
|
2021-07-10 16:07:37 +00:00
|
|
|
|
2023-05-17 04:46:48 +00:00
|
|
|
fn get_key_value(key: &str) -> Option<KeyValue> {
|
|
|
|
let conn = get_connection().ok()?;
|
|
|
|
dsl::kv_table
|
|
|
|
.filter(kv_table::key.eq(key))
|
|
|
|
.first::<KeyValue>(&*conn)
|
|
|
|
.ok()
|
2023-02-13 01:29:49 +00:00
|
|
|
}
|
2021-07-10 16:07:37 +00:00
|
|
|
}
|
|
|
|
|
2023-05-17 04:46:48 +00:00
|
|
|
fn get_connection() -> Result<DBConnection, anyhow::Error> {
|
|
|
|
let conn = KV_HOLDER
|
|
|
|
.read()
|
|
|
|
.database
|
|
|
|
.as_ref()
|
|
|
|
.expect("KVStore is not init")
|
|
|
|
.get_connection()
|
|
|
|
.map_err(|_e| anyhow!("Get KV connection error"))?;
|
|
|
|
Ok(conn)
|
|
|
|
}
|
|
|
|
|
2021-12-12 13:18:23 +00:00
|
|
|
#[derive(Clone, Debug, Default, Queryable, Identifiable, Insertable, AsChangeset)]
|
2021-07-10 16:07:37 +00:00
|
|
|
#[table_name = "kv_table"]
|
|
|
|
#[primary_key(key)]
|
|
|
|
pub struct KeyValue {
|
2023-02-13 01:29:49 +00:00
|
|
|
pub key: String,
|
2023-05-17 04:46:48 +00:00
|
|
|
pub value: Option<String>,
|
2021-07-10 16:07:37 +00:00
|
|
|
}
|
|
|
|
|
2021-07-11 07:33:19 +00:00
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
2023-05-17 04:46:48 +00:00
|
|
|
use serde::{Deserialize, Serialize};
|
|
|
|
use tempfile::TempDir;
|
|
|
|
|
2023-02-13 01:29:49 +00:00
|
|
|
use crate::kv::KV;
|
2021-07-10 16:07:37 +00:00
|
|
|
|
2023-05-17 04:46:48 +00:00
|
|
|
#[derive(Serialize, Deserialize, Clone, Eq, PartialEq, Debug)]
|
|
|
|
struct Person {
|
|
|
|
name: String,
|
|
|
|
age: i32,
|
|
|
|
}
|
|
|
|
|
2023-02-13 01:29:49 +00:00
|
|
|
#[test]
|
|
|
|
fn kv_store_test() {
|
2023-05-17 04:46:48 +00:00
|
|
|
let tempdir = TempDir::new().unwrap();
|
|
|
|
let path = tempdir.into_path();
|
|
|
|
KV::init(path.to_str().unwrap()).unwrap();
|
2021-07-11 07:33:19 +00:00
|
|
|
|
2023-02-13 01:29:49 +00:00
|
|
|
KV::set_str("1", "hello".to_string());
|
|
|
|
assert_eq!(KV::get_str("1").unwrap(), "hello");
|
|
|
|
assert_eq!(KV::get_str("2"), None);
|
2021-07-11 07:33:19 +00:00
|
|
|
|
2023-05-17 04:46:48 +00:00
|
|
|
KV::set_bool("1", true).unwrap();
|
2023-02-13 01:29:49 +00:00
|
|
|
assert!(KV::get_bool("1"));
|
|
|
|
assert!(!KV::get_bool("2"));
|
2023-05-17 04:46:48 +00:00
|
|
|
|
|
|
|
KV::set_i64("1", 1).unwrap();
|
|
|
|
assert_eq!(KV::get_i64("1").unwrap(), 1);
|
|
|
|
assert_eq!(KV::get_i64("2"), None);
|
|
|
|
|
|
|
|
let person = Person {
|
|
|
|
name: "nathan".to_string(),
|
|
|
|
age: 30,
|
|
|
|
};
|
|
|
|
KV::set_object("1", person.clone()).unwrap();
|
|
|
|
assert_eq!(KV::get_object::<Person>("1").unwrap(), person);
|
2023-02-13 01:29:49 +00:00
|
|
|
}
|
2021-07-10 16:07:37 +00:00
|
|
|
}
|