Compare commits

..

No commits in common. "cd0a92fe94b05fe94455e0eae1ea849457cbd6de" and "efd3124b29dda68715a1f50b1c641ca7fa6ca6c7" have entirely different histories.

2 changed files with 6 additions and 21 deletions

View file

@ -1,6 +1,6 @@
[package] [package]
name = "jsondb" name = "jsondb"
version = "0.1.1" version = "0.1.0"
edition = "2021" edition = "2021"
authors = ["xenofem <xenofem@xeno.science>"] authors = ["xenofem <xenofem@xeno.science>"]

View file

@ -47,12 +47,9 @@ pub struct JsonDb<T: Schema> {
/// other fields of the corresponding schema version; earlier versions /// other fields of the corresponding schema version; earlier versions
/// will be migrated to the current version automatically. /// will be migrated to the current version automatically.
pub trait Schema: DeserializeOwned + Serialize { pub trait Schema: DeserializeOwned + Serialize {
/// Previous schema that can be migrated into the new schema const VERSION: u32;
type Prev: Schema + Into<Self>; type Prev: Schema + Into<Self>;
/// Schema version number
const VERSION: u32 = Self::Prev::VERSION + 1;
fn parse(s: &str) -> Result<Self, Error> { fn parse(s: &str) -> Result<Self, Error> {
let Version { version } = serde_json::from_str(s)?; let Version { version } = serde_json::from_str(s)?;
match version.cmp(&Self::VERSION) { match version.cmp(&Self::VERSION) {
@ -67,25 +64,11 @@ pub trait Schema: DeserializeOwned + Serialize {
/// ///
/// Implementing this will automatically implement [`Schema`], with /// Implementing this will automatically implement [`Schema`], with
/// version number `0` and `Self` as the previous version. /// version number `0` and `Self` as the previous version.
pub trait SchemaV0: DeserializeOwned + Serialize { pub trait SchemaV0: DeserializeOwned + Serialize {}
/// Set this to false if your version 0 is a pre-`JsonDb` schema
/// that does not include a version number.
const EXPECT_VERSION_NUMBER: bool = true;
}
impl<T: SchemaV0> Schema for T { impl<T: SchemaV0> Schema for T {
type Prev = Self;
const VERSION: u32 = 0; const VERSION: u32 = 0;
type Prev = Self;
fn parse(s: &str) -> Result<Self, Error> {
if Self::EXPECT_VERSION_NUMBER {
let Version { version } = serde_json::from_str(s)?;
if version != 0 {
return Err(Error::UnknownVersion(version));
}
}
Ok(serde_json::from_str(s)?)
}
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -233,6 +216,7 @@ mod tests {
last_updated: i64, last_updated: i64,
} }
impl Schema for V1 { impl Schema for V1 {
const VERSION: u32 = 1;
type Prev = V0; type Prev = V0;
} }
impl From<V0> for V1 { impl From<V0> for V1 {
@ -264,6 +248,7 @@ mod tests {
} }
} }
impl Schema for V2 { impl Schema for V2 {
const VERSION: u32 = 2;
type Prev = V1; type Prev = V1;
} }
impl From<V1> for V2 { impl From<V1> for V2 {