use crate::{
defensive,
storage::{storage_prefix, transactional::with_transaction_opaque_err},
traits::{
Defensive, GetStorageVersion, NoStorageVersionSet, PalletInfoAccess, SafeMode,
StorageVersion,
},
weights::{RuntimeDbWeight, Weight, WeightMeter},
};
use alloc::vec::Vec;
use codec::{Decode, Encode, MaxEncodedLen};
use core::marker::PhantomData;
use impl_trait_for_tuples::impl_for_tuples;
use subsoil::arithmetic::traits::Bounded;
use subsoil::core::Get;
use subsoil::io::{hashing::twox_128, storage::clear_prefix, KillStorageResult};
use subsoil::runtime::traits::Zero;
pub struct VersionedMigration<const FROM: u16, const TO: u16, Inner, Pallet, Weight> {
_marker: PhantomData<(Inner, Pallet, Weight)>,
}
#[derive(Encode, Decode)]
pub enum VersionedPostUpgradeData {
MigrationExecuted(alloc::vec::Vec<u8>),
Noop,
}
impl<
const FROM: u16,
const TO: u16,
Inner: crate::traits::UncheckedOnRuntimeUpgrade,
Pallet: GetStorageVersion<InCodeStorageVersion = StorageVersion> + PalletInfoAccess,
DbWeight: Get<RuntimeDbWeight>,
> crate::traits::OnRuntimeUpgrade for VersionedMigration<FROM, TO, Inner, Pallet, DbWeight>
{
#[cfg(feature = "try-runtime")]
fn pre_upgrade() -> Result<alloc::vec::Vec<u8>, subsoil::runtime::TryRuntimeError> {
let on_chain_version = Pallet::on_chain_storage_version();
if on_chain_version == FROM {
Ok(VersionedPostUpgradeData::MigrationExecuted(Inner::pre_upgrade()?).encode())
} else {
Ok(VersionedPostUpgradeData::Noop.encode())
}
}
fn on_runtime_upgrade() -> Weight {
let on_chain_version = Pallet::on_chain_storage_version();
if on_chain_version == FROM {
log::info!(
"🚚 Pallet {:?} VersionedMigration migrating storage version from {:?} to {:?}.",
Pallet::name(),
FROM,
TO
);
let weight = Inner::on_runtime_upgrade();
StorageVersion::new(TO).put::<Pallet>();
weight.saturating_add(DbWeight::get().reads_writes(1, 1))
} else {
log::warn!(
"🚚 Pallet {:?} VersionedMigration migration {}->{} can be removed; on-chain is already at {:?}.",
Pallet::name(),
FROM,
TO,
on_chain_version
);
DbWeight::get().reads(1)
}
}
#[cfg(feature = "try-runtime")]
fn post_upgrade(
versioned_post_upgrade_data_bytes: alloc::vec::Vec<u8>,
) -> Result<(), subsoil::runtime::TryRuntimeError> {
use codec::DecodeAll;
match <VersionedPostUpgradeData>::decode_all(&mut &versioned_post_upgrade_data_bytes[..])
.map_err(|_| "VersionedMigration post_upgrade failed to decode PreUpgradeData")?
{
VersionedPostUpgradeData::MigrationExecuted(inner_bytes) => {
Inner::post_upgrade(inner_bytes)
},
VersionedPostUpgradeData::Noop => Ok(()),
}
}
}
pub trait StoreInCodeStorageVersion<T: GetStorageVersion + PalletInfoAccess> {
fn store_in_code_storage_version();
}
impl<T: GetStorageVersion<InCodeStorageVersion = StorageVersion> + PalletInfoAccess>
StoreInCodeStorageVersion<T> for StorageVersion
{
fn store_in_code_storage_version() {
let version = <T as GetStorageVersion>::in_code_storage_version();
version.put::<T>();
}
}
impl<T: GetStorageVersion<InCodeStorageVersion = NoStorageVersionSet> + PalletInfoAccess>
StoreInCodeStorageVersion<T> for NoStorageVersionSet
{
fn store_in_code_storage_version() {
StorageVersion::default().put::<T>();
}
}
pub trait PalletVersionToStorageVersionHelper {
fn migrate(db_weight: &RuntimeDbWeight) -> Weight;
}
impl<T: GetStorageVersion + PalletInfoAccess> PalletVersionToStorageVersionHelper for T
where
T::InCodeStorageVersion: StoreInCodeStorageVersion<T>,
{
fn migrate(db_weight: &RuntimeDbWeight) -> Weight {
const PALLET_VERSION_STORAGE_KEY_POSTFIX: &[u8] = b":__PALLET_VERSION__:";
fn pallet_version_key(name: &str) -> [u8; 32] {
crate::storage::storage_prefix(name.as_bytes(), PALLET_VERSION_STORAGE_KEY_POSTFIX)
}
subsoil::io::storage::clear(&pallet_version_key(<T as PalletInfoAccess>::name()));
<T::InCodeStorageVersion as StoreInCodeStorageVersion<T>>::store_in_code_storage_version();
db_weight.writes(2)
}
}
#[cfg_attr(all(not(feature = "tuples-96"), not(feature = "tuples-128")), impl_for_tuples(64))]
#[cfg_attr(all(feature = "tuples-96", not(feature = "tuples-128")), impl_for_tuples(96))]
#[cfg_attr(feature = "tuples-128", impl_for_tuples(128))]
impl PalletVersionToStorageVersionHelper for T {
fn migrate(db_weight: &RuntimeDbWeight) -> Weight {
let mut weight = Weight::zero();
for_tuples!( #( weight = weight.saturating_add(T::migrate(db_weight)); )* );
weight
}
}
pub fn migrate_from_pallet_version_to_storage_version<
Pallets: PalletVersionToStorageVersionHelper,
>(
db_weight: &RuntimeDbWeight,
) -> Weight {
Pallets::migrate(db_weight)
}
pub struct RemovePallet<P: Get<&'static str>, DbWeight: Get<RuntimeDbWeight>>(
PhantomData<(P, DbWeight)>,
);
impl<P: Get<&'static str>, DbWeight: Get<RuntimeDbWeight>> topsoil_core::traits::OnRuntimeUpgrade
for RemovePallet<P, DbWeight>
{
fn on_runtime_upgrade() -> topsoil_core::weights::Weight {
let hashed_prefix = twox_128(P::get().as_bytes());
let keys_removed = match clear_prefix(&hashed_prefix, None) {
KillStorageResult::AllRemoved(value) => value,
KillStorageResult::SomeRemaining(value) => {
log::error!(
"`clear_prefix` failed to remove all keys for {}. THIS SHOULD NEVER HAPPEN! 🚨",
P::get()
);
value
},
} as u64;
log::info!("Removed {} {} keys 🧹", keys_removed, P::get());
DbWeight::get().reads_writes(keys_removed + 1, keys_removed)
}
#[cfg(feature = "try-runtime")]
fn pre_upgrade() -> Result<alloc::vec::Vec<u8>, subsoil::runtime::TryRuntimeError> {
use crate::storage::unhashed::contains_prefixed_key;
let hashed_prefix = twox_128(P::get().as_bytes());
match contains_prefixed_key(&hashed_prefix) {
true => log::info!("Found {} keys pre-removal 👀", P::get()),
false => log::warn!(
"Migration RemovePallet<{}> can be removed (no keys found pre-removal).",
P::get()
),
};
Ok(alloc::vec::Vec::new())
}
#[cfg(feature = "try-runtime")]
fn post_upgrade(_state: alloc::vec::Vec<u8>) -> Result<(), subsoil::runtime::TryRuntimeError> {
use crate::storage::unhashed::contains_prefixed_key;
let hashed_prefix = twox_128(P::get().as_bytes());
match contains_prefixed_key(&hashed_prefix) {
true => {
log::error!("{} has keys remaining post-removal ❗", P::get());
return Err("Keys remaining post-removal, this should never happen 🚨".into());
},
false => log::info!("No {} keys found post-removal 🎉", P::get()),
};
Ok(())
}
}
pub struct RemoveStorage<P: Get<&'static str>, S: Get<&'static str>, DbWeight: Get<RuntimeDbWeight>>(
PhantomData<(P, S, DbWeight)>,
);
impl<P: Get<&'static str>, S: Get<&'static str>, DbWeight: Get<RuntimeDbWeight>>
topsoil_core::traits::OnRuntimeUpgrade for RemoveStorage<P, S, DbWeight>
{
fn on_runtime_upgrade() -> topsoil_core::weights::Weight {
let hashed_prefix = storage_prefix(P::get().as_bytes(), S::get().as_bytes());
let keys_removed = match clear_prefix(&hashed_prefix, None) {
KillStorageResult::AllRemoved(value) => value,
KillStorageResult::SomeRemaining(value) => {
log::error!(
"`clear_prefix` failed to remove all keys for storage `{}` from pallet `{}`. THIS SHOULD NEVER HAPPEN! 🚨",
S::get(), P::get()
);
value
},
} as u64;
log::info!("Removed `{}` `{}` `{}` keys 🧹", keys_removed, P::get(), S::get());
DbWeight::get().reads_writes(keys_removed + 1, keys_removed)
}
#[cfg(feature = "try-runtime")]
fn pre_upgrade() -> Result<alloc::vec::Vec<u8>, subsoil::runtime::TryRuntimeError> {
use crate::storage::unhashed::contains_prefixed_key;
let hashed_prefix = storage_prefix(P::get().as_bytes(), S::get().as_bytes());
match contains_prefixed_key(&hashed_prefix) {
true => log::info!("Found `{}` `{}` keys pre-removal 👀", P::get(), S::get()),
false => log::warn!(
"Migration RemoveStorage<{}, {}> can be removed (no keys found pre-removal).",
P::get(),
S::get()
),
};
Ok(Default::default())
}
#[cfg(feature = "try-runtime")]
fn post_upgrade(_state: alloc::vec::Vec<u8>) -> Result<(), subsoil::runtime::TryRuntimeError> {
use crate::storage::unhashed::contains_prefixed_key;
let hashed_prefix = storage_prefix(P::get().as_bytes(), S::get().as_bytes());
match contains_prefixed_key(&hashed_prefix) {
true => {
log::error!("`{}` `{}` has keys remaining post-removal ❗", P::get(), S::get());
return Err("Keys remaining post-removal, this should never happen 🚨".into());
},
false => log::info!("No `{}` `{}` keys found post-removal 🎉", P::get(), S::get()),
};
Ok(())
}
}
pub trait SteppedMigration {
type Cursor: codec::FullCodec + codec::MaxEncodedLen;
type Identifier: codec::FullCodec + codec::MaxEncodedLen;
fn id() -> Self::Identifier;
fn max_steps() -> Option<u32> {
None
}
fn migrating_prefixes() -> Option<impl IntoIterator<Item = Vec<u8>>> {
None::<core::iter::Empty<_>>
}
fn step(
cursor: Option<Self::Cursor>,
meter: &mut WeightMeter,
) -> Result<Option<Self::Cursor>, SteppedMigrationError>;
fn transactional_step(
mut cursor: Option<Self::Cursor>,
meter: &mut WeightMeter,
) -> Result<Option<Self::Cursor>, SteppedMigrationError> {
with_transaction_opaque_err(move || match Self::step(cursor, meter) {
Ok(new_cursor) => {
cursor = new_cursor;
subsoil::runtime::TransactionOutcome::Commit(Ok(cursor))
},
Err(err) => subsoil::runtime::TransactionOutcome::Rollback(Err(err)),
})
.map_err(|()| SteppedMigrationError::Failed)?
}
#[cfg(feature = "try-runtime")]
fn pre_upgrade() -> Result<Vec<u8>, subsoil::runtime::TryRuntimeError> {
Ok(Vec::new())
}
#[cfg(feature = "try-runtime")]
fn post_upgrade(_state: Vec<u8>) -> Result<(), subsoil::runtime::TryRuntimeError> {
Ok(())
}
}
#[derive(Debug, Encode, Decode, MaxEncodedLen, PartialEq, Eq, scale_info::TypeInfo)]
pub enum SteppedMigrationError {
InsufficientWeight {
required: Weight,
},
InvalidCursor,
Failed,
}
#[derive(MaxEncodedLen, Encode, Decode)]
pub struct MigrationId<const N: usize> {
pub pallet_id: [u8; N],
pub version_from: u8,
pub version_to: u8,
}
#[impl_trait_for_tuples::impl_for_tuples(8)]
pub trait MigrationStatusHandler {
fn started() {}
fn completed() {}
}
pub trait FailedMigrationHandler {
fn failed(migration: Option<u32>) -> FailedMigrationHandling;
}
pub struct FreezeChainOnFailedMigration;
impl FailedMigrationHandler for FreezeChainOnFailedMigration {
fn failed(_migration: Option<u32>) -> FailedMigrationHandling {
FailedMigrationHandling::KeepStuck
}
}
pub struct EnterSafeModeOnFailedMigration<SM, Else: FailedMigrationHandler>(
PhantomData<(SM, Else)>,
);
impl<Else: FailedMigrationHandler, SM: SafeMode> FailedMigrationHandler
for EnterSafeModeOnFailedMigration<SM, Else>
where
<SM as SafeMode>::BlockNumber: Bounded,
{
fn failed(migration: Option<u32>) -> FailedMigrationHandling {
let entered = if SM::is_entered() {
SM::extend(Bounded::max_value())
} else {
SM::enter(Bounded::max_value())
};
if entered.is_err() {
Else::failed(migration)
} else {
FailedMigrationHandling::KeepStuck
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FailedMigrationHandling {
ForceUnstuck,
KeepStuck,
Ignore,
}
pub trait MultiStepMigrator {
fn ongoing() -> bool;
fn step() -> Weight;
}
impl MultiStepMigrator for () {
fn ongoing() -> bool {
false
}
fn step() -> Weight {
Weight::zero()
}
}
pub trait SteppedMigrations {
fn len() -> u32;
fn nth_id(n: u32) -> Option<Vec<u8>>;
fn nth_max_steps(n: u32) -> Option<Option<u32>>;
fn nth_step(
n: u32,
cursor: Option<Vec<u8>>,
meter: &mut WeightMeter,
) -> Option<Result<Option<Vec<u8>>, SteppedMigrationError>>;
fn nth_transactional_step(
n: u32,
cursor: Option<Vec<u8>>,
meter: &mut WeightMeter,
) -> Option<Result<Option<Vec<u8>>, SteppedMigrationError>>;
fn nth_migrating_prefixes(n: u32) -> Option<Option<Vec<Vec<u8>>>>;
#[cfg(feature = "try-runtime")]
fn nth_pre_upgrade(n: u32) -> Option<Result<Vec<u8>, subsoil::runtime::TryRuntimeError>>;
#[cfg(feature = "try-runtime")]
fn nth_post_upgrade(
n: u32,
_state: Vec<u8>,
) -> Option<Result<(), subsoil::runtime::TryRuntimeError>>;
fn cursor_max_encoded_len() -> usize;
fn identifier_max_encoded_len() -> usize;
#[cfg(feature = "std")]
fn integrity_test() -> Result<(), &'static str> {
use crate::ensure;
let l = Self::len();
for n in 0..l {
ensure!(Self::nth_id(n).is_some(), "id is None");
ensure!(Self::nth_max_steps(n).is_some(), "steps is None");
ensure!(
Self::nth_step(n, Some(vec![]), &mut WeightMeter::new()).is_some(),
"steps is None"
);
ensure!(
Self::nth_transactional_step(n, Some(vec![]), &mut WeightMeter::new()).is_some(),
"steps is None"
);
}
Ok(())
}
}
impl SteppedMigrations for () {
fn len() -> u32 {
0
}
fn nth_id(_n: u32) -> Option<Vec<u8>> {
None
}
fn nth_max_steps(_n: u32) -> Option<Option<u32>> {
None
}
fn nth_step(
_n: u32,
_cursor: Option<Vec<u8>>,
_meter: &mut WeightMeter,
) -> Option<Result<Option<Vec<u8>>, SteppedMigrationError>> {
None
}
fn nth_transactional_step(
_n: u32,
_cursor: Option<Vec<u8>>,
_meter: &mut WeightMeter,
) -> Option<Result<Option<Vec<u8>>, SteppedMigrationError>> {
None
}
fn nth_migrating_prefixes(_n: u32) -> Option<Option<Vec<Vec<u8>>>> {
None
}
#[cfg(feature = "try-runtime")]
fn nth_pre_upgrade(_n: u32) -> Option<Result<Vec<u8>, subsoil::runtime::TryRuntimeError>> {
Some(Ok(Vec::new()))
}
#[cfg(feature = "try-runtime")]
fn nth_post_upgrade(
_n: u32,
_state: Vec<u8>,
) -> Option<Result<(), subsoil::runtime::TryRuntimeError>> {
Some(Ok(()))
}
fn cursor_max_encoded_len() -> usize {
0
}
fn identifier_max_encoded_len() -> usize {
0
}
}
impl<T: SteppedMigration> SteppedMigrations for T {
fn len() -> u32 {
1
}
fn nth_id(n: u32) -> Option<Vec<u8>> {
n.is_zero()
.then(|| T::id().encode())
.defensive_proof("nth_id should only be called with n==0")
}
fn nth_max_steps(n: u32) -> Option<Option<u32>> {
n.is_zero()
.then(|| T::max_steps())
.defensive_proof("nth_max_steps should only be called with n==0")
}
fn nth_step(
n: u32,
cursor: Option<Vec<u8>>,
meter: &mut WeightMeter,
) -> Option<Result<Option<Vec<u8>>, SteppedMigrationError>> {
if !n.is_zero() {
defensive!("nth_step should only be called with n==0");
return None;
}
let cursor = match cursor {
Some(cursor) => match T::Cursor::decode(&mut &cursor[..]) {
Ok(cursor) => Some(cursor),
Err(_) => return Some(Err(SteppedMigrationError::InvalidCursor)),
},
None => None,
};
Some(T::step(cursor, meter).map(|cursor| cursor.map(|cursor| cursor.encode())))
}
fn nth_transactional_step(
n: u32,
cursor: Option<Vec<u8>>,
meter: &mut WeightMeter,
) -> Option<Result<Option<Vec<u8>>, SteppedMigrationError>> {
if n != 0 {
defensive!("nth_transactional_step should only be called with n==0");
return None;
}
let cursor = match cursor {
Some(cursor) => match T::Cursor::decode(&mut &cursor[..]) {
Ok(cursor) => Some(cursor),
Err(_) => return Some(Err(SteppedMigrationError::InvalidCursor)),
},
None => None,
};
Some(
T::transactional_step(cursor, meter).map(|cursor| cursor.map(|cursor| cursor.encode())),
)
}
fn nth_migrating_prefixes(n: u32) -> Option<Option<Vec<Vec<u8>>>> {
n.is_zero()
.then(|| T::migrating_prefixes().map(|p| p.into_iter().collect()))
.defensive_proof("nth_migrating_prefixes should only be called with n==0")
}
#[cfg(feature = "try-runtime")]
fn nth_pre_upgrade(n: u32) -> Option<Result<Vec<u8>, subsoil::runtime::TryRuntimeError>> {
if n != 0 {
defensive!("nth_pre_upgrade should only be called with n==0");
}
Some(T::pre_upgrade())
}
#[cfg(feature = "try-runtime")]
fn nth_post_upgrade(
n: u32,
state: Vec<u8>,
) -> Option<Result<(), subsoil::runtime::TryRuntimeError>> {
if n != 0 {
defensive!("nth_post_upgrade should only be called with n==0");
}
Some(T::post_upgrade(state))
}
fn cursor_max_encoded_len() -> usize {
T::Cursor::max_encoded_len()
}
fn identifier_max_encoded_len() -> usize {
T::Identifier::max_encoded_len()
}
}
#[impl_trait_for_tuples::impl_for_tuples(1, 30)]
impl SteppedMigrations for Tuple {
fn len() -> u32 {
for_tuples!( #( Tuple::len() )+* )
}
fn nth_id(n: u32) -> Option<Vec<u8>> {
let mut i = 0;
for_tuples!( #(
if (i + Tuple::len()) > n {
return Tuple::nth_id(n - i)
}
i += Tuple::len();
)* );
None
}
fn nth_step(
n: u32,
cursor: Option<Vec<u8>>,
meter: &mut WeightMeter,
) -> Option<Result<Option<Vec<u8>>, SteppedMigrationError>> {
let mut i = 0;
for_tuples!( #(
if (i + Tuple::len()) > n {
return Tuple::nth_step(n - i, cursor, meter)
}
i += Tuple::len();
)* );
None
}
fn nth_transactional_step(
n: u32,
cursor: Option<Vec<u8>>,
meter: &mut WeightMeter,
) -> Option<Result<Option<Vec<u8>>, SteppedMigrationError>> {
let mut i = 0;
for_tuples! ( #(
if (i + Tuple::len()) > n {
return Tuple::nth_transactional_step(n - i, cursor, meter)
}
i += Tuple::len();
)* );
None
}
fn nth_migrating_prefixes(n: u32) -> Option<Option<Vec<Vec<u8>>>> {
let mut i = 0;
for_tuples!( #(
let len = Tuple::len() as u32;
if (i + len) > n {
return Tuple::nth_migrating_prefixes(n - i);
}
i += len;
)* );
None
}
#[cfg(feature = "try-runtime")]
fn nth_pre_upgrade(n: u32) -> Option<Result<Vec<u8>, subsoil::runtime::TryRuntimeError>> {
let mut i = 0;
for_tuples! ( #(
if (i + Tuple::len()) > n {
return Tuple::nth_pre_upgrade(n - i)
}
i += Tuple::len();
)* );
None
}
#[cfg(feature = "try-runtime")]
fn nth_post_upgrade(
n: u32,
state: Vec<u8>,
) -> Option<Result<(), subsoil::runtime::TryRuntimeError>> {
let mut i = 0;
for_tuples! ( #(
if (i + Tuple::len()) > n {
return Tuple::nth_post_upgrade(n - i, state)
}
i += Tuple::len();
)* );
None
}
fn nth_max_steps(n: u32) -> Option<Option<u32>> {
let mut i = 0;
for_tuples!( #(
if (i + Tuple::len()) > n {
return Tuple::nth_max_steps(n - i)
}
i += Tuple::len();
)* );
None
}
fn cursor_max_encoded_len() -> usize {
let mut max_len = 0;
for_tuples!( #(
max_len = max_len.max(Tuple::cursor_max_encoded_len());
)* );
max_len
}
fn identifier_max_encoded_len() -> usize {
let mut max_len = 0;
for_tuples!( #(
max_len = max_len.max(Tuple::identifier_max_encoded_len());
)* );
max_len
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{assert_ok, storage::unhashed};
#[derive(Decode, Encode, MaxEncodedLen, Eq, PartialEq)]
#[allow(dead_code)]
pub enum Either<L, R> {
Left(L),
Right(R),
}
pub struct M0;
impl SteppedMigration for M0 {
type Cursor = ();
type Identifier = u8;
fn id() -> Self::Identifier {
0
}
fn step(
_cursor: Option<Self::Cursor>,
_meter: &mut WeightMeter,
) -> Result<Option<Self::Cursor>, SteppedMigrationError> {
log::info!("M0");
unhashed::put(&[0], &());
Ok(None)
}
fn migrating_prefixes() -> Option<impl IntoIterator<Item = Vec<u8>>> {
Some(vec![b"M0_prefix1".to_vec(), b"M0_prefix2".to_vec()])
}
}
pub struct M1;
impl SteppedMigration for M1 {
type Cursor = ();
type Identifier = u8;
fn id() -> Self::Identifier {
1
}
fn step(
_cursor: Option<Self::Cursor>,
_meter: &mut WeightMeter,
) -> Result<Option<Self::Cursor>, SteppedMigrationError> {
log::info!("M1");
unhashed::put(&[1], &());
Ok(None)
}
fn max_steps() -> Option<u32> {
Some(1)
}
fn migrating_prefixes() -> Option<impl IntoIterator<Item = Vec<u8>>> {
Some(vec![b"M1_prefix".to_vec()])
}
}
pub struct M2;
impl SteppedMigration for M2 {
type Cursor = ();
type Identifier = u8;
fn id() -> Self::Identifier {
2
}
fn step(
_cursor: Option<Self::Cursor>,
_meter: &mut WeightMeter,
) -> Result<Option<Self::Cursor>, SteppedMigrationError> {
log::info!("M2");
unhashed::put(&[2], &());
Ok(None)
}
fn max_steps() -> Option<u32> {
Some(2)
}
fn migrating_prefixes() -> Option<impl IntoIterator<Item = Vec<u8>>> {
Some(vec![b"M2_prefix1".to_vec(), b"M2_prefix2".to_vec(), b"M2_prefix3".to_vec()])
}
}
pub struct M3;
impl SteppedMigration for M3 {
type Cursor = ();
type Identifier = u8;
fn id() -> Self::Identifier {
3
}
fn step(
_cursor: Option<Self::Cursor>,
_meter: &mut WeightMeter,
) -> Result<Option<Self::Cursor>, SteppedMigrationError> {
log::info!("M3");
Ok(None)
}
}
pub struct F0;
impl SteppedMigration for F0 {
type Cursor = ();
type Identifier = u8;
fn id() -> Self::Identifier {
4
}
fn step(
_cursor: Option<Self::Cursor>,
_meter: &mut WeightMeter,
) -> Result<Option<Self::Cursor>, SteppedMigrationError> {
log::info!("F0");
unhashed::put(&[3], &());
Err(SteppedMigrationError::Failed)
}
}
type Triple = (M0, (M1, M2));
type Hextuple = (Triple, Triple);
#[test]
fn singular_migrations_work() {
assert_eq!(M0::max_steps(), None);
assert_eq!(M1::max_steps(), Some(1));
assert_eq!(M2::max_steps(), Some(2));
assert_eq!(<(M0, M1)>::nth_max_steps(0), Some(None));
assert_eq!(<(M0, M1)>::nth_max_steps(1), Some(Some(1)));
assert_eq!(<(M0, M1, M2)>::nth_max_steps(2), Some(Some(2)));
assert_eq!(<(M0, M1)>::nth_max_steps(2), None);
}
#[test]
fn tuple_migrations_work() {
assert_eq!(<() as SteppedMigrations>::len(), 0);
assert_eq!(<((), ((), ())) as SteppedMigrations>::len(), 0);
assert_eq!(<Triple as SteppedMigrations>::len(), 3);
assert_eq!(<Hextuple as SteppedMigrations>::len(), 6);
assert_eq!(<Triple as SteppedMigrations>::nth_id(0), Some(0u8.encode()));
assert_eq!(<Triple as SteppedMigrations>::nth_id(1), Some(1u8.encode()));
assert_eq!(<Triple as SteppedMigrations>::nth_id(2), Some(2u8.encode()));
subsoil::io::TestExternalities::default().execute_with(|| {
for n in 0..3 {
<Triple as SteppedMigrations>::nth_step(
n,
Default::default(),
&mut WeightMeter::new(),
);
}
});
}
#[test]
fn integrity_test_works() {
subsoil::io::TestExternalities::default().execute_with(|| {
assert_ok!(<() as SteppedMigrations>::integrity_test());
assert_ok!(<M0 as SteppedMigrations>::integrity_test());
assert_ok!(<M1 as SteppedMigrations>::integrity_test());
assert_ok!(<M2 as SteppedMigrations>::integrity_test());
assert_ok!(<Triple as SteppedMigrations>::integrity_test());
assert_ok!(<Hextuple as SteppedMigrations>::integrity_test());
});
}
#[test]
fn transactional_rollback_works() {
subsoil::io::TestExternalities::default().execute_with(|| {
assert_ok!(<(M0, F0) as SteppedMigrations>::nth_transactional_step(
0,
Default::default(),
&mut WeightMeter::new()
)
.unwrap());
assert!(unhashed::exists(&[0]));
let _g = crate::StorageNoopGuard::new();
assert!(<(M0, F0) as SteppedMigrations>::nth_transactional_step(
1,
Default::default(),
&mut WeightMeter::new()
)
.unwrap()
.is_err());
assert!(<(F0, M1) as SteppedMigrations>::nth_transactional_step(
0,
Default::default(),
&mut WeightMeter::new()
)
.unwrap()
.is_err());
});
}
#[test]
fn nth_migrating_prefixes_works() {
assert_eq!(
M0::nth_migrating_prefixes(0),
Some(Some(vec![b"M0_prefix1".to_vec(), b"M0_prefix2".to_vec()]))
);
assert_eq!(M3::nth_migrating_prefixes(0), Some(None));
type Pair = (M0, M1);
assert_eq!(Pair::len(), 2);
assert_eq!(
Pair::nth_migrating_prefixes(0),
Some(Some(vec![b"M0_prefix1".to_vec(), b"M0_prefix2".to_vec()]))
);
assert_eq!(Pair::nth_migrating_prefixes(1), Some(Some(vec![b"M1_prefix".to_vec()])));
assert_eq!(Pair::nth_migrating_prefixes(2), None);
type Nested = (M0, (M1, M2));
assert_eq!(Nested::len(), 3);
assert_eq!(
Nested::nth_migrating_prefixes(0),
Some(Some(vec![b"M0_prefix1".to_vec(), b"M0_prefix2".to_vec()]))
);
assert_eq!(Nested::nth_migrating_prefixes(1), Some(Some(vec![b"M1_prefix".to_vec()])));
assert_eq!(
Nested::nth_migrating_prefixes(2),
Some(Some(vec![
b"M2_prefix1".to_vec(),
b"M2_prefix2".to_vec(),
b"M2_prefix3".to_vec()
]))
);
assert_eq!(Nested::nth_migrating_prefixes(3), None);
}
}