use crate::database::Database; use crate::migration::Migration; use geoffrey_models::models::locations::LocationDb; use geoffrey_models::GeoffreyDatabaseModel; use json::JsonValue; pub(crate) struct PosAndNetherMigration {} impl Migration for PosAndNetherMigration { fn up(db: &Database) -> crate::error::Result<()> { let loc_tree = db.db.open_tree(LocationDb::tree())?; for entry in loc_tree.iter() { let (id, loc_ivec) = entry?; let mut loc = json::parse(std::str::from_utf8(&loc_ivec).unwrap()).unwrap(); let z = loc["position"]["y"].clone(); loc["position"]["y"] = 65.into(); loc["position"]["z"] = z; loc["tunnel"] = JsonValue::Null; loc_tree.insert(id, loc.to_string().as_bytes())?; } Ok(()) } fn down(db: &Database) -> crate::error::Result<()> { let loc_tree = db.db.open_tree(LocationDb::tree())?; for entry in loc_tree.iter() { let (id, loc_ivec) = entry?; let mut loc = json::parse(std::str::from_utf8(&loc_ivec).unwrap()).unwrap(); loc["position"]["y"] = loc["position"]["z"].clone(); loc["position"]["z"].clear(); // Clear out the tunnel entry, there is not a great way to convert loc["tunnel"] = JsonValue::Null; loc_tree.insert(id, loc.to_string().as_bytes())?; } Ok(()) } fn version() -> u64 { 2 } } #[cfg(test)] mod tests { use crate::database::Database; use crate::migration::migration_2::PosAndNetherMigration; use crate::migration::Migration; use geoffrey_models::models::locations::LocationDb; use geoffrey_models::GeoffreyDatabaseModel; use sled::IVec; use std::path::Path; #[test] fn test_migration_2() { let db = Database::new(Path::new("../migration_2_db/")).unwrap(); let loc_tree = db.db.open_tree(LocationDb::tree()).unwrap(); let old_loc_format = json::parse( r#"{ "id": 55, "name": "Test", "position": { "x": 55, "y": 55, "dimension": "Overworld" }, "loc_data": "Base" }"#, ) .unwrap(); loc_tree .insert(IVec::from(vec![55]), old_loc_format.to_string().as_bytes()) .unwrap(); PosAndNetherMigration::up(&db).unwrap(); let new_loc = loc_tree.get(IVec::from(vec![55])).unwrap().unwrap(); let new_loc = json::parse(std::str::from_utf8(&new_loc).unwrap()).unwrap(); assert_eq!(new_loc["position"]["y"], 65); assert_eq!(new_loc["position"]["z"], 55); drop(db); std::fs::remove_dir_all("../migration_2_db").unwrap(); } }