Updating Type without losing data

Good afternoon, I need to add a property to my fantasy teams type and I don’t want to lose all my data (again).

Is there a documented procedure I can follow to add a property and ensure nothing is lost in the pre and post upgrade process?

Any help would be greatly appreciated.

James

3 Likes

Instead of trying to upgrade and keep the data, should I just back it up and recreate it after it’s deleted?

I would say yes. There is no specific way defined for this. I usually do this by backing up data in stable variable and then reassigning the values from back up data to original structures.

1 Like

Thank you for confirming sir.

1 Like

@jamesbeadle,

I am guessing you are using Motoko, and in that case you are stuck with pre-upgrade, and post-upgrade methods to ensure you keep the data.

Rust has two libraries that make you able to persist data without pre-and-post upgrade calls, but the learning curve to master Rust on the IC is much higher than the one for Motoko.

So, I have some good news for you that may be useful there is a library that can persist data even if you use Motoko, if you haven’t see it is called Motoko-Hash-Map by @ZhenyaUsenko:

It works very well, and I do recommend it.

Let me know about your fantasy game, sounds fun!

Joseph

If you’re changing the types and they’re not backward compatible (you can use didc to compare the old and new candid, see here: https://internetcomputer.org/docs/current/motoko/main/upgrades/#upgrade-safety ), then you can migrate the old data when reloading it in postupgrade:

Write a function that maps the old type to new and pass the data through this in postupgrade. Then remove this function for future upgrades since you wouldn’t need it again.

2 Likes