Geoffrey-rs/geoffrey_db/src/migration/migration_3.rs

100 lines
2.6 KiB
Rust

use crate::database::Database;
use crate::migration::Migration;
use geoffrey_models::models::locations::LocationDb;
use geoffrey_models::GeoffreyDatabaseModel;
pub(crate) struct TunnelToPortalMigration {}
impl Migration for TunnelToPortalMigration {
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 tunnel = loc["tunnel"].clone();
loc["portal"] = tunnel;
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();
let portal = loc["portal"].clone();
loc["tunnel"] = portal;
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_3::TunnelToPortalMigration;
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_3() {
let db = Database::new(Path::new("../migration_3_db/")).unwrap();
let loc_tree = db.db.open_tree(LocationDb::tree()).unwrap();
let old_loc = json::parse(
r#"{
"id": 55,
"name": "Test",
"position": {
"x": 55,
"y": 55,
"z": 55,
"dimension": "Overworld"
},
"tunnel": {
"x": 8,
"z": 8
},
"loc_data": "Base"
}"#,
)
.unwrap();
loc_tree
.insert(IVec::from(vec![55]), old_loc.to_string().as_bytes())
.unwrap();
TunnelToPortalMigration::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["portal"]["x"], 8);
assert_eq!(new_loc["portal"]["z"], 8);
drop(db);
std::fs::remove_dir_all("../migration_3_db").unwrap();
}
}