use crate::version::ORIGIN_UUID;
use serde::{Deserialize, Serialize};
pub trait SnapshotEntity {
const DIALECT: &'static str;
const SNAPSHOT_VERSION: &'static str;
}
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Snapshot<E> {
pub version: String,
pub dialect: String,
pub id: String,
pub prev_ids: Vec<String>,
pub ddl: Vec<E>,
#[serde(default)]
pub renames: Vec<String>,
}
impl<E: SnapshotEntity> Default for Snapshot<E> {
fn default() -> Self {
Self::new()
}
}
impl<E: SnapshotEntity> Snapshot<E> {
#[must_use]
pub fn new() -> Self {
Self {
version: E::SNAPSHOT_VERSION.to_string(),
dialect: E::DIALECT.to_string(),
id: uuid::Uuid::new_v4().to_string(),
prev_ids: vec![ORIGIN_UUID.to_string()],
ddl: Vec::new(),
renames: Vec::new(),
}
}
#[must_use]
pub fn with_prev_ids(prev_ids: Vec<String>) -> Self {
let mut snapshot = Self::new();
snapshot.prev_ids = prev_ids;
snapshot
}
}
impl<E> Snapshot<E> {
pub fn add_entity(&mut self, entity: E) {
self.ddl.push(entity);
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.ddl.is_empty()
}
}
impl<E> Snapshot<E>
where
E: Serialize + for<'de> Deserialize<'de>,
{
pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
serde_json::from_str(json)
}
pub fn to_json(&self) -> Result<String, serde_json::Error> {
serde_json::to_string_pretty(self)
}
pub fn load(path: &std::path::Path) -> std::io::Result<Self> {
let contents = std::fs::read_to_string(path)?;
serde_json::from_str(&contents)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))
}
pub fn save(&self, path: &std::path::Path) -> std::io::Result<()> {
let json = serde_json::to_string_pretty(self)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::write(path, json)
}
}