Upgrades: Revise Saved Data on Purpose
Chapters
- Write V2 beside V1
- Say how V1 becomes V2
- Native first, then the real upgrade
Transcript
Write V2 beside V1
This app is deployed with root memory version one. The root saves no fields, and it has one child, Scores. We want the root to save a revision number. Version one is shipped, so its file stays as it is. Version two is a new file with the complete declaration. Data now has the revision field. The children are written out again, and the Scores slot still names Scores version one. The root changed. Scores did not, so its version number stays. The selector now exports version two as current. Both modules stay in the source. Service code keeps saying current and follows along. Version one remains for the converter to read.
Say how V1 becomes V2
The converter lives in the root's memory folder. It takes the version one root and returns the version two root. Its first closure receives the old data, which was empty, and returns the new data with revision two. Its second closure handles the children. It takes Scores out of the old slot and attaches it to the new one. The scores themselves are never touched. Two more edits connect it. The root attribute lists version one under previous. That is the only older contract this build will accept. Then open, which restore calls, asks which root the canister saved. If it is version one, it runs the converter. Otherwise it opens version two directly. Either way it ends by binding the services.
Native first, then the real upgrade
A native test covers the converter itself. It installs a version one root by hand, saves ninety-one under key seven, and calls open. Afterward the Scores module is the very same one, key seven still holds ninety-one, and the generation is two. On PocketIC the test starts from an installed version one with two values. A version two build that forgot to declare its predecessor is refused. Another build converts successfully and then fails in its restore callback. The whole upgrade is undone. The canister is version one again, with generation one and both values. The proper version two build upgrades. Generation is two, and keys seven and eight still hold their values. From here the old build is no longer accepted. The test tries to install version one again and it is refused. Later version two releases upgrade normally, and the app stays writable. One planning rule remains. The whole conversion runs inside the single upgrade. There is no background migration that continues afterward. So design a revision that fits, and move unchanged collections across whole, as this converter moved Scores, in place of rebuilding them row by row.