use chrono::{DateTime, NaiveDate, NaiveDateTime, Utc};
pub type Timestamp = DateTime<Utc>;
pub type NaiveTimestamp = NaiveDateTime;
pub type Date = NaiveDate;
pub type JsonValue = serde_json::Value;
#[doc(hidden)]
pub trait StoreSource {
fn store_value(&self, key: &str) -> Option<&JsonValue>;
}
impl StoreSource for JsonValue {
fn store_value(&self, key: &str) -> Option<&JsonValue> {
self.get(key).filter(|v| !v.is_null())
}
}
impl StoreSource for Option<JsonValue> {
fn store_value(&self, key: &str) -> Option<&JsonValue> {
self.as_ref()?.store_value(key)
}
}
#[doc(hidden)]
pub trait StoreTarget {
fn store_object(&mut self) -> &mut serde_json::Map<String, JsonValue>;
}
impl StoreTarget for JsonValue {
fn store_object(&mut self) -> &mut serde_json::Map<String, JsonValue> {
if !self.is_object() {
*self = JsonValue::Object(serde_json::Map::new());
}
self.as_object_mut().expect("made an object above")
}
}
impl StoreTarget for Option<JsonValue> {
fn store_object(&mut self) -> &mut serde_json::Map<String, JsonValue> {
self.get_or_insert_with(|| JsonValue::Object(serde_json::Map::new()))
.store_object()
}
}
#[doc(hidden)]
pub fn store_set(store: &mut impl StoreTarget, key: &str, value: impl serde::Serialize) {
let value = serde_json::to_value(value).unwrap_or(JsonValue::Null);
store.store_object().insert(key.to_owned(), value);
}
#[doc(hidden)]
pub fn store_get<T: serde::de::DeserializeOwned>(store: &impl StoreSource, key: &str) -> Option<T> {
serde_json::from_value(store.store_value(key)?.clone()).ok()
}
#[derive(Debug, Clone, PartialEq)]
pub enum Value {
Null,
Bool(bool),
Int(i64),
Float(f64),
Text(String),
Bytes(Vec<u8>),
Timestamp(Timestamp),
Date(Date),
Json(JsonValue),
Decimal(super::Decimal),
Uuid(uuid::Uuid),
#[doc(hidden)]
List(Vec<Value>),
}
impl Value {
pub fn is_null(&self) -> bool {
matches!(self, Value::Null)
}
pub fn to_text(&self) -> String {
match self {
Value::Null => String::new(),
Value::Bool(v) => v.to_string(),
Value::Int(v) => v.to_string(),
Value::Float(v) => v.to_string(),
Value::Text(v) => v.clone(),
Value::Bytes(v) => String::from_utf8_lossy(v).into_owned(),
Value::Timestamp(v) => v.to_rfc3339(),
Value::Date(v) => v.to_string(),
Value::Json(v) => v.to_string(),
Value::Decimal(v) => v.to_string(),
Value::Uuid(v) => v.to_string(),
Value::List(items) => items
.iter()
.map(Value::to_text)
.collect::<Vec<_>>()
.join(", "),
}
}
}
pub trait ToValue {
fn to_value(&self) -> Value;
}
impl<T: ToValue + ?Sized> ToValue for &T {
fn to_value(&self) -> Value {
(**self).to_value()
}
}
impl<T: ToValue> ToValue for Option<T> {
fn to_value(&self) -> Value {
self.as_ref().map_or(Value::Null, ToValue::to_value)
}
}
impl ToValue for Value {
fn to_value(&self) -> Value {
self.clone()
}
}
macro_rules! to_value {
($variant:ident: $($t:ty),*) => {$(
impl ToValue for $t {
fn to_value(&self) -> Value {
Value::$variant((*self).into())
}
}
)*};
}
to_value!(Int: i8, i16, i32, i64, u8, u16, u32);
to_value!(Float: f32, f64);
to_value!(Bool: bool);
to_value!(Timestamp: Timestamp);
impl ToValue for NaiveTimestamp {
fn to_value(&self) -> Value {
Value::Timestamp(self.and_utc())
}
}
impl ToValue for Date {
fn to_value(&self) -> Value {
Value::Date(*self)
}
}
impl ToValue for str {
fn to_value(&self) -> Value {
Value::Text(self.to_owned())
}
}
impl ToValue for String {
fn to_value(&self) -> Value {
Value::Text(self.clone())
}
}
impl ToValue for uuid::Uuid {
fn to_value(&self) -> Value {
Value::Uuid(*self)
}
}
impl ToValue for super::Decimal {
fn to_value(&self) -> Value {
Value::Decimal(self.clone())
}
}
impl ToValue for JsonValue {
fn to_value(&self) -> Value {
Value::Json(self.clone())
}
}
impl ToValue for Vec<u8> {
fn to_value(&self) -> Value {
Value::Bytes(self.clone())
}
}
#[cfg(feature = "postgres")]
mod pg {
pub trait Decode:
for<'r> sqlx::Decode<'r, sqlx::Postgres> + sqlx::Type<sqlx::Postgres>
{
}
impl<T> Decode for T where T: for<'r> sqlx::Decode<'r, sqlx::Postgres> + sqlx::Type<sqlx::Postgres> {}
}
#[cfg(not(feature = "postgres"))]
mod pg {
pub trait Decode {}
impl<T> Decode for T {}
}
#[cfg(feature = "sqlite")]
mod sqlite {
pub trait Decode: for<'r> sqlx::Decode<'r, sqlx::Sqlite> + sqlx::Type<sqlx::Sqlite> {}
impl<T> Decode for T where T: for<'r> sqlx::Decode<'r, sqlx::Sqlite> + sqlx::Type<sqlx::Sqlite> {}
}
#[cfg(not(feature = "sqlite"))]
mod sqlite {
pub trait Decode {}
impl<T> Decode for T {}
}
pub trait FromColumn: pg::Decode + sqlite::Decode + Send + 'static {}
impl<T> FromColumn for T where T: pg::Decode + sqlite::Decode + Send + 'static {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reads_store_settings() {
let cache = serde_json::json!({"days": 3, "text": "Hi", "gone": null, "wrong": "x"});
assert_eq!(store_get::<i64>(&cache, "days"), Some(3));
assert_eq!(store_get::<String>(&cache, "text").as_deref(), Some("Hi"));
assert_eq!(
store_get::<String>(&cache, "gone"),
None,
"null reads as unset"
);
assert_eq!(store_get::<i64>(&cache, "missing"), None);
assert_eq!(
store_get::<i64>(&cache, "wrong"),
None,
"the wrong type reads as unset"
);
assert_eq!(store_get::<i64>(&None::<JsonValue>, "days"), None);
let mut empty: Option<JsonValue> = None;
store_set(&mut empty, "days", 4);
assert_eq!(empty, Some(serde_json::json!({"days": 4})));
let mut cache = cache;
store_set(&mut cache, "text", "Bye");
assert_eq!(cache["text"], "Bye");
assert_eq!(cache["days"], 3, "other settings stay");
}
}