Skip to content

Commit

Permalink
Fix: MultiIndex key deserializes to remaining key plus pk (Map-like)
Browse files Browse the repository at this point in the history
  • Loading branch information
maurolacy committed Oct 27, 2021
1 parent 868b850 commit 5fb6ec5
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 2 deletions.
65 changes: 65 additions & 0 deletions packages/storage-plus/src/indexed_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -684,6 +684,71 @@ mod test {
assert_eq!(data3, marias[1].1);
}

#[test]
fn range_de_composite_key_by_multi_index() {
let mut store = MockStorage::new();

let indexes = DataCompositeMultiIndex {
name_age: MultiIndex::new(
|d, k| index_triple(&d.name, d.age, k),
"data",
"data__name_age",
),
};
let map = IndexedMap::new("data", indexes);

// save data
let data1 = Data {
name: "Maria".to_string(),
last_name: "".to_string(),
age: 42,
};
let pk1: &[u8] = b"5627";
map.save(&mut store, pk1, &data1).unwrap();

let data2 = Data {
name: "Juan".to_string(),
last_name: "Perez".to_string(),
age: 13,
};
let pk2: &[u8] = b"5628";
map.save(&mut store, pk2, &data2).unwrap();

let data3 = Data {
name: "Maria".to_string(),
last_name: "Young".to_string(),
age: 24,
};
let pk3: &[u8] = b"5629";
map.save(&mut store, pk3, &data3).unwrap();

let data4 = Data {
name: "Maria Luisa".to_string(),
last_name: "Bemberg".to_string(),
age: 43,
};
let pk4: &[u8] = b"5630";
map.save(&mut store, pk4, &data4).unwrap();

let marias: Vec<_> = map
.idx
.name_age
.sub_prefix_de(b"Maria".to_vec())
.range_de(&store, None, None, Order::Descending)
.collect::<StdResult<_>>()
.unwrap();
let count = marias.len();
assert_eq!(2, count);

// Remaining age of the index keys, plus pks (sorted by age descending)
assert_eq!((42, pk1.to_vec()), marias[0].0);
assert_eq!((24, pk3.to_vec()), marias[1].0);

// Data
assert_eq!(data1, marias[0].1);
assert_eq!(data3, marias[1].1);
}

#[test]
fn unique_index_enforced() {
let mut store = MockStorage::new();
Expand Down
5 changes: 3 additions & 2 deletions packages/storage-plus/src/indexes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,8 @@ fn deserialize_multi_v<T: DeserializeOwned>(
.ok_or_else(|| StdError::generic_err("pk not found"))?;
let v = from_slice::<T>(&v)?;

Ok((pk.into(), v))
// FIXME: Return `key` here instead of `pk` (be consistent with `deserialize_multi_kv` and `Map` behaviour)
Ok((pk.to_vec(), v))
}

fn deserialize_multi_kv<K: KeyDeserialize, T: DeserializeOwned>(
Expand All @@ -147,7 +148,7 @@ fn deserialize_multi_kv<K: KeyDeserialize, T: DeserializeOwned>(
.ok_or_else(|| StdError::generic_err("pk not found"))?;
let v = from_slice::<T>(&v)?;

Ok((K::from_vec(pk.to_vec())?, v))
Ok((K::from_vec(key)?, v))
}

impl<'a, K, T> Index<T> for MultiIndex<'a, K, T>
Expand Down

0 comments on commit 5fb6ec5

Please sign in to comment.