migrating-motoko-actors
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseMotoko Actor Migrations
Motoko Actor 迁移
Expert guidance for migrating actor state across canister upgrades with orthogonal persistence.
关于使用正交持久化在 canister 升级过程中迁移 actor 状态的专家指南。
Critical: Never use classical persistence or pre/post upgrade
重要:切勿使用经典持久化或 pre/post upgrade
Do not use classical (legacy) persistence or / . They are error-prone, can leave canisters stuck if they trap, and do not scale.
system func preupgradesystem func postupgradeAlso do not use the legacy actor-attached syntax. This skill covers mops-managed migrations. When a change requires an explicit migration, write it as a timestamped file in ; the chain replays automatically.
(with migration = ...)src/backend/migrations/切勿使用经典(legacy)持久化或 / 。这些方式容易出错,一旦触发 trap 就可能让 canister 陷入卡死状态,而且无法扩展。
system func preupgradesystem func postupgrade也不要使用 legacy 的 actor-attached 语法。本 skill 涵盖 mops 管理的迁移。当变更需要显式迁移时,将其编写为 中带时间戳的文件;迁移链会自动重放。
(with migration = ...)src/backend/migrations/How stable state is initialized
stable 状态如何初始化
Stable actor fields have no initializers in the actor body. The chain in is what gives them values: the runtime walks it in lexicographic order, running every file on a fresh install and only the files not yet applied to the canister on an upgrade.
src/backend/migrations/Actor body 中的 stable 字段没有初始化器。 中的迁移链负责为它们提供值:runtime 会按字典序遍历该链,在全新安装时运行每个文件,在升级时只运行尚未应用到 canister 的文件。
src/backend/migrations/When to Use This Skill
何时使用本 skill
- Planning or implementing a canister upgrade that changes actor state
- Deciding between implicit vs explicit migration
- Writing or refactoring a migration function
- Introducing stable state for the first time (a migration with , or fold it into the first one if that is still pending)
OldActor = {}
- 规划或实现会更改 actor 状态的 canister 升级
- 决定使用隐式迁移还是显式迁移
- 编写或重构 migration function
- 首次引入 stable 状态(使用 的 migration,或在首个 migration 尚未应用时将初始化逻辑合并到其中)
OldActor = {}
Migration Folder Rules
Migration 目录规则
- All migrations live in . The full chain replays in lexicographic filename order on fresh install; on upgrade, only entries newer than the deployed tail run. (The directory is declared as
src/backend/migrations/underchain = ...in[canisters.<name>.migrations]; an imported project using a non-default canister name may place it elsewhere — readmops.tomlrather than assuming.)mops.toml - At most one pending migration per build (in
check-limit = 1). If a migration is already pending (not yet applied), edit that file to fold in further changes instead of adding another.mops.tomlcompares the deployedmops checkbaseline and names the latest pending file to fold into when the limit is exceeded. Where a hosting platform owns the migrations section and.most, never edit them to clear an error.check-limit - Name new files with just the UTC timestamp, no suffix: . The timestamp must sort after every existing file. Do NOT encode the change in the name (no
YYYYMMDD_HHMMSS.mo,AddPriority,AddTags, …) — any feature-ish name tempts you to add another file for the next change instead of editing the one pending file.Init - Never modify, delete, or rename a migration that was already applied. Applied migrations are tracked by module name, so a rename makes the runtime treat the file as never applied, and an edit to an already-applied file never executes. Some platforms enforce this by making applied migrations read-only, in which case writes to them simply fail. A migration that was not applied yet is pending: edit it rather than add a second migration for the same change.
- Migrations must be self-contained. Inline BOTH old types AND new types in the migration file. Only and mops package imports are allowed — never
mo:core/...or any project module. The chain replays forever; a frozen migration that imported../typesbecomes wrong the momentTypes.Notechanges in an incompatible way. Component-owned opaque state is the reason package imports are allowed:NotefromAccessControl.initState()can only be constructed by importing the package.mo:caffeineai-authorization/access-control - automatically verifies upgrade compatibility.
mops check --fix
- 所有 migration 都位于 。 全新安装时,完整迁移链会按文件名的字典序重放;升级时,只运行比已部署链尾更新的条目。(该目录通过
src/backend/migrations/中mops.toml下的[canisters.<name>.migrations]声明;导入的项目如果使用非默认 canister 名称,可能将该目录放在其他位置——请阅读chain = ...,不要想当然。)mops.toml - 每次构建最多只能有一个待应用 migration(在 中设置
mops.toml)。如果已有 migration 尚未应用,请直接编辑该文件以合并后续变更,而不是再添加一个。check-limit = 1会将已部署的mops check基线进行比较;当超出限制时,它会指出应合并变更的最新待应用文件。如果托管平台负责管理 migrations 配置段和.most,切勿通过编辑它们来清除错误。check-limit - 仅使用 UTC 时间戳命名新文件,不要添加后缀: 。时间戳必须排在所有现有文件之后。不要在名称中编码变更内容(不要使用
YYYYMMDD_HHMMSS.mo、AddPriority、AddTags等名称)——带功能含义的名称会诱使你在下一次变更时再添加文件,而不是编辑当前待应用文件。Init - 绝不要修改、删除或重命名已经应用的 migration。 已应用的 migration 会按 module 名称跟踪,因此重命名会让 runtime 将该文件视为从未应用,而编辑已经应用的文件则永远不会执行。有些平台通过将已应用 migration 设为只读来强制执行此规则,此时写入会直接失败。尚未应用的 migration 属于待应用状态:请编辑它,不要为同一变更添加第二个 migration。
- Migration 必须自包含。 在 migration 文件中同时内联 old types 和 new types。只允许使用 和 mops package imports——绝不能使用
mo:core/...或任何项目 module。迁移链会永久重放;如果冻结的 migration 导入了../types,那么Types.Note一旦发生不兼容变更,该文件就会立即失效。组件持有的 opaque state 是允许 package imports 的原因:只有导入Notepackage,才能构造mo:caffeineai-authorization/access-control。AccessControl.initState() - 会自动验证升级兼容性。
mops check --fix
Two Kinds of Migration
两类迁移
1. Implicit migration (no code)
1. 隐式迁移(无需代码)
The runtime allows the upgrade if the new program is compatible with the old. No migration function needed.
Do NOT add a migration file for changes in the implicit list below. Every migration file replays forever on fresh install; adding a no-op file bloats the chain, slows fresh installs, and creates a frozen artifact you can never delete. A long enough chain becomes undeployable in a way no retry recovers, andwill not warn you. Fewer migrations are always better.mops checkIdentity body = no migration. If yourbody would just be(old : OldActor) : NewActor(or rebuild the same record field-by-field with no transformation), the change is stable-compatible — delete the file.old
Allowed without explicit migration (typical compatible changes):
- Changing mutability of a field (to
varor vice versa)let - Adding variant constructors
- Changing to
Nat(and other safe supertypes)Int - Other changes that satisfy Motoko stable subtyping
Require explicit migration:
- Removing any actor field the previous version exposes — consume it in , omit from
OldActorNewActor - Promoting to or other lossy supertypes
Any - Renaming fields (map old to new in migration)
- Non-trivial transformations (e.g. to
Int, restructuring records)Float - Adding new stable fields (initial values must come from the migration; no inline initializers allowed)
- Introducing stable state for the first time (the migration supplies the initial values; the actor declares stable fields with types only, no inline initializers)
如果新程序与旧程序兼容,runtime 会允许升级。无需 migration function。
不要为以下隐式列表中的变更添加 migration 文件。 每个 migration 文件都会在全新安装时永久重放;添加空操作文件会膨胀迁移链、拖慢全新安装,并创造一个永远无法删除的冻结产物。迁移链足够长后,会变得无法部署,且任何重试都无法恢复,而也不会发出警告。migration 越少永远越好。mops check恒等函数体 = 无需 migration。 如果你的函数体只会返回(old : OldActor) : NewActor(或逐字段重建同一个 record 且不做任何转换),则该变更与 stable 兼容——请删除该文件。old
无需显式 migration 的典型兼容变更:
- 更改字段的可变性(改为
var,或反之)let - 添加 variant 构造器
- 将 改为
Nat(以及其他安全超类型)Int - 满足 Motoko stable subtyping 的其他变更
需要显式迁移:
- 移除上一版本公开的任意 actor 字段——在 中消费它,并从
OldActor中省略NewActor - 提升为 或其他有损超类型
Any - 重命名字段(在 migration 中将旧字段映射到新字段)
- 非平凡转换(例如将 转换为
Int、重构 record)Float - 添加新的 stable 字段(初始值必须来自 migration;不允许使用内联初始化器)
- 首次引入 stable 状态(migration 提供初始值;actor 仅声明 stable 字段的类型,不使用内联初始化器)
2. Explicit migration (migration function)
2. 显式迁移(migration function)
Use when the new state shape or types are not a simple compatible extension of the old.
Extend the pending migration if there is one; otherwise add a new timestamped file to . The chain replays automatically.
src/backend/migrations/Rules:
- Migration function type: . Both record types must be stable (no shared/local functions; use primitive types, records, variants, Option, Map, List, etc.).
(old : OldActor) : NewActor - Domain : record of old stable fields (names and types as in the previous version). If the retired actor is missing a field the domain expects, the upgrade traps and is aborted.
OldActor - Codomain : record of new stable fields; each field must exist in the new actor with the same name and a supertype of the codomain type. Use
NewActororvar x = ...in the output to match the actor'sx = ...vsvar.let - On fresh install, the entire chain replays in order starting from an empty actor (for the first migration); on upgrade, only entries newer than the deployed tail run. Exception: in a project converted from legacy persistence the first file's
OldActor = {}is the pre-conversion stable shape, notOldActor— leave it alone (see{}).troubleshooting-motoko-migrations - Each field's value comes from the migration body. The actor body has no initializers in enhanced mode.
NewActor - List every stable field in both and
OldActor(including unchanged ones) is the canonical form for clarity. A partialNewActor/OldActorthat lists only the fields being changed (subset form) is also supported: unchanged fields carry through automatically. Either way, a field inNewActorbut not inOldActoris an explicit discard (possible data loss).NewActor - If the migration function traps, the upgrade is aborted and the canister remains on the old version. Keep the migration pure and free of operations that can trap unexpectedly.
Multi-step upgrades (e.g. v1 to v2 to v3): Each upgrade step has one migration from the previously deployed version. The next version can use a new migration (or none if the change is stable-compatible).
如果新状态结构或类型并非旧状态的简单兼容扩展,则使用此方式。
如果已有待应用 migration,则扩展它;否则,在 中添加一个带时间戳的新文件。迁移链会自动重放。
src/backend/migrations/规则:
- Migration function 类型:。两种 record 类型都必须是 stable(不得包含 shared/local functions;可使用 primitive types、records、variants、Option、Map、List 等)。
(old : OldActor) : NewActor - Domain :由旧 stable 字段组成的 record(字段名和类型与上一版本一致)。如果退役 actor 缺少 Domain 所期望的字段,升级会触发 trap 并中止。
OldActor - Codomain :由新 stable 字段组成的 record;每个字段都必须以相同名称存在于新 actor 中,且 actor 中对应字段的类型必须是 Codomain 类型的超类型。根据 actor 的
NewActor或var,在输出中使用let或var x = ...。x = ... - 全新安装时,完整迁移链会从空 actor 开始按顺序重放(首个 migration 使用 );升级时,只运行比已部署链尾更新的条目。例外:从 legacy 持久化转换而来的项目,其首个文件的
OldActor = {}是转换前的 stable shape,而不是OldActor——不要修改它(参见{})。troubleshooting-motoko-migrations - 每个 字段的值都来自 migration body。在 enhanced mode 下,actor body 中没有初始化器。
NewActor - 在 和
OldActor中都列出每一个 stable 字段(包括未变更的字段)是清晰表达的标准形式。也支持只列出待变更字段的部分形式(subset form),未变更字段会自动继承。无论采用哪种形式,NewActor中存在但OldActor中不存在的字段都表示显式丢弃(可能造成数据丢失)。NewActor - 如果 migration function 触发 trap,升级会中止,canister 将继续运行旧版本。保持 migration 纯粹,并避免执行可能意外触发 trap 的操作。
多步骤升级(例如 v1 到 v2 到 v3):每个升级步骤都包含一条从先前已部署版本出发的 migration。下一版本可以使用新的 migration,或者在变更与 stable 兼容时不使用 migration。
Authoring a migration
编写 migration
Pick a bare UTC-timestamp filename (, no suffix) that sorts after every existing entry, then write the module:
YYYYMMDD_HHMMSS.momotoko
module {
type OldActor = { /* old stable fields, inlined */ };
type NewActor = { /* new stable fields */ };
public func migration(old : OldActor) : NewActor {
{ /* produce new fields from old */ };
};
};
- Must be a exporting
module(the function name is required — the chain runner discovers it by name).public func migration(old : OldActor) : NewActor - Both and
OldActormust be inlined in the file — no project imports.NewActor
选择一个仅含 UTC 时间戳的文件名(,无后缀),并确保其排在所有现有条目之后,然后编写 module:
YYYYMMDD_HHMMSS.momotoko
module {
type OldActor = { /* old stable fields, inlined */ };
type NewActor = { /* new stable fields */ };
public func migration(old : OldActor) : NewActor {
{ /* produce new fields from old */ };
};
};- 必须是一个导出 的
public func migration(old : OldActor) : NewActor(函数名是必需的——chain runner 通过该名称发现它)。module - 和
OldActor都必须内联在文件中——不得导入项目 module。NewActor
Actor body: types only, no initializers
Actor body:仅声明类型,不使用初始化器
Stable vars are declared with types, no initial values. Transient let/var fields use initializers as usual.
This no-initializer rule applies to enhanced-migration projects (this skill's subject), where the migration chain owns initial values. In a plain project without the enhanced-migration chain, stable fields are initialized with inline values in the actor body as usual (e.g.).actor { let m = Map.empty<Nat, Text>(); }
motoko
actor {
let tasks : Map.Map<Text, Task>;
var nextId : Nat;
transient var cache = List.empty<Text>();
};
Initial values come from the migration chain. When you introduce stable state for the first time, write a migration whose and enumerates every stable field declared in . The migration body must produce a value for each. Missing fields surface as compatibility warnings and break subsequent upgrades.
OldActor = {}NewActormain.moIf an example anywhere shows inline initializers likeorlet accessControlState = AccessControl.initState();directly in the actor body, it predates enhanced migration. Under enhanced migration that is a compile error (M0014, M0250). Treat such examples as state-shape hints only: copy the field name and type into your actor (without initializer), and move the initializer expression into the migration function'slet users = Map.empty<Principal, User>();output.NewActor
Stable vars 仅声明类型,不设置初始值。Transient let/var 字段照常使用初始化器。
此无初始化器规则仅适用于 enhanced-migration 项目(本 skill 的主题),其中初始值由 migration chain 管理。在没有 enhanced-migration chain 的普通项目中,stable 字段照常在 actor body 中使用内联值进行初始化(例如)。actor { let m = Map.empty<Nat, Text>(); }
motoko
actor {
let tasks : Map.Map<Text, Task>;
var nextId : Nat;
transient var cache = List.empty<Text>();
};初始值来自 migration chain。首次引入 stable 状态时,编写一份 的 migration,并让 枚举 中声明的每一个 stable 字段。Migration body 必须为每个字段生成一个值。缺失字段会触发兼容性警告,并破坏后续升级。
OldActor = {}NewActormain.mo如果任何示例直接展示 actor body 中的内联初始化器,例如或let accessControlState = AccessControl.initState();,则该示例早于 enhanced migration。在 enhanced migration 下,这是编译错误(M0014、M0250)。请仅将这类示例视为状态结构提示:将字段名和类型复制到 actor 中(不带初始化器),并把初始化表达式移动到 migration function 的let users = Map.empty<Principal, User>();输出中。NewActor
Stable-Compatible (definition)
Stable-compatible(定义)
Old signature is stable-compatible with new if, for every stable field in the old signature:
id : T- The new signature has a stable field such that T is a stable subtype of U (the old value can be used as the new field's initial value without loss of data).
id : U - The new signature may include additional fields not present in the old one (each supplied by a migration).
- Matching fields may differ in mutability (vs non-
var).var
So: you can widen types (e.g. to ) and change mutability without an explicit migration. You cannot remove fields, rename them, or narrow types. Adding a stable field always requires a migration: inline initializers are not allowed, so the new field's initial value must come from a migration file's .
NatIntNewActor如果对于旧签名中的每个 stable 字段 ,旧签名都与新签名 stable-compatible,则满足以下条件:
id : T- 新签名包含一个 stable 字段 ,并且 T 是 U 的 stable subtype(旧值可以在不丢失数据的情况下用作新字段的初始值)。
id : U - 新签名可以包含旧签名中不存在的额外字段(每个字段都由 migration 提供)。
- 匹配的字段可以具有不同的可变性(与非
var)。var
因此,可以拓宽类型(例如将 改为 )并更改可变性,而无需显式 migration。不能移除字段、重命名或收窄类型。添加 stable 字段始终需要 migration:不允许使用内联初始化器,因此新字段的初始值必须来自 migration 文件的 。
NatIntNewActorPatterns
模式
Add record field with default
使用默认值添加 record 字段
Use to add a field to every element:
record with newField = valuemotoko
// Add required field zipCode to each taxpayer
old.taxPayers.map<Nat, OldTaxPayer, NewTaxPayer>(
func(_id, oldTaxPayer) { { oldTaxPayer with zipCode = "" } }
);
For a new optional field, set it to :
nullmotoko
{ task with var status = task.status; var assignee = null : ?Principal }
使用 为每个元素添加字段:
record with newField = valuemotoko
// Add required field zipCode to each taxpayer
old.taxPayers.map<Nat, OldTaxPayer, NewTaxPayer>(
func(_id, oldTaxPayer) { { oldTaxPayer with zipCode = "" } }
);如果要添加新的可选字段,将其设为 :
nullmotoko
{ task with var status = task.status; var assignee = null : ?Principal }Add or extend variant type
添加或扩展 variant 类型
Adding a variant tag -- cast the old value to the new variant type:
motoko
var status = bounty.status : NewTaskStatus // OldTaskStatus had #open;#claimed;#completed; New adds #expired
Replacing a Bool with a variant:
motoko
var status = if (task.completed) { #completed } else { #pending };
添加 variant tag——将旧值转换为新的 variant 类型:
motoko
var status = bounty.status : NewTaskStatus // OldTaskStatus had #open;#claimed;#completed; New adds #expired使用 variant 替换 Bool:
motoko
var status = if (task.completed) { #completed } else { #pending };Map over a collection
遍历集合
Transform each value in a with :
Mapmap<K, OldV, NewV>(func(key, oldVal) { ... })motoko
let todos = old.todos.map<TaskID, OldTask, NewTask>(
func(_, task) {
{
task with
due = 0;
var status = if (task.completed) { #completed } else { #pending };
};
}
);
{ var todos; var nextTaskId = old.nextTaskId };
使用 转换 中的每个值:
map<K, OldV, NewV>(func(key, oldVal) { ... })Mapmotoko
let todos = old.todos.map<TaskID, OldTask, NewTask>(
func(_, task) {
{
task with
due = 0;
var status = if (task.completed) { #completed } else { #pending };
};
}
);
{ var todos; var nextTaskId = old.nextTaskId };Add new top-level stable field (computed from old state)
添加新的顶层 stable 字段(根据旧状态计算)
Include the new field in the migration output and compute it from old fields:
motoko
let times = List.repeat<Time.Time>(0, old.messages.size());
{ var messages = old.messages; var times };
将新字段包含在 migration 输出中,并根据旧字段计算:
motoko
let times = List.repeat<Time.Time>(0, old.messages.size());
{ var messages = old.messages; var times };Restructure: change shape of state
重构:更改状态结构
When the new state has a different structure, provide a transformation function from the old field type to the new one and implement it according to the application's migration logic. Build the new value in the migration from the old state and return a record that matches NewActor.
当新状态具有不同结构时,提供从旧字段类型到新类型的转换函数,并按照应用的 migration 逻辑实现它。根据旧状态构建新值,并返回与 匹配的 record。
NewActorChange type of a field
更改字段类型
Rename/conceptual change -- e.g. to :
artist : Textartists : Set.Set<Text>motoko
{ oldPainting with artists = Set.singleton<Text>(oldPainting.artist) }
重命名或概念性变更——例如将 改为 :
artist : Textartists : Set.Set<Text>motoko
{ oldPainting with artists = Set.singleton<Text>(oldPainting.artist) }Rename or change type of a single field
重命名或更改单个字段的类型
Input record uses old name/type, output record uses new name/type:
motoko
// src/backend/migrations/YYYYMMDD_HHMMSS.mo
import Int "mo:core/Int";
module {
type OldActor = { var state : Int };
type NewActor = { var newState : Float };
public func migration(old : OldActor) : NewActor {
{ var newState = old.state.toFloat() };
};
};输入 record 使用旧名称和类型,输出 record 使用新名称和类型:
motoko
// src/backend/migrations/YYYYMMDD_HHMMSS.mo
import Int "mo:core/Int";
module {
type OldActor = { var state : Int };
type NewActor = { var newState : Float };
public func migration(old : OldActor) : NewActor {
{ var newState = old.state.toFloat() };
};
};Drop a field intentionally
有意丢弃字段
Consume it in the migration input but do not include it in the output. Expect a compiler warning; ensure the loss is intentional.
在 migration 输入中消费该字段,但不要将其包含在输出中。预期会出现编译器警告;请确保数据丢失是有意为之。
Add a new field
添加新字段
Add the field to with type only (no initializer) AND add it to the next migration's with a value computed from old fields or a constant. The actor body cannot supply the initial value under enhanced migration.
main.moNewActor在 中仅以类型(无初始化器)添加该字段,同时在下一份 migration 的 中加入该字段,其值由旧字段计算或使用常量。在 enhanced migration 下,actor body 无法提供初始值。
main.moNewActorMigration-Time Semantics
Migration 执行时的语义
- The migration function runs once at upgrade time, in the upgrade context. Values like in the migration body are the time of the upgrade, not of each original record creation.
Time.now() - Do not use constants or magic values in migrations; derive defaults from the migration input or from well-defined application types.
- Migration function 在升级时运行一次,运行于 upgrade context 中。Migration body 中的 等值表示升级时间,而不是每条原始记录的创建时间。
Time.now() - 不要在 migration 中使用常量或 magic values;应从 migration 输入或定义明确的应用类型中派生默认值。
Compatibility and Tooling
兼容性与工具
The upgrade safety check compares the new actor body against the last deployed stable signature: a file (an encoded snapshot of the stable signature — field names and types) referenced from under . When that is configured, picks it up automatically. Hosted platforms typically wire this up for you and keep the previous alongside the project.
.mostmops.toml[canisters.<name>.check-stable]mops check --fix.mostFor the check to pass: the new migration's must match the previously deployed signature, and its must match (or be a stable supertype of) the new actor body.
OldActorNewActorTo derive deterministically: your equals the of the file that precedes yours in (lex-order), or if yours is the first file in the chain. applies only when the chain starts from an empty canister — a project converted from legacy persistence starts from its pre-conversion stable shape instead, and its existing first file already reflects that.
OldActorOldActorNewActorsrc/backend/migrations/{}{}升级安全检查会将新 actor body 与最后部署的 stable signature 进行比较。后者是一个 文件(stable signature 的编码快照,包含字段名称和类型),通过 中 引用。完成此项配置后, 会自动识别它。托管平台通常会代为配置,并保留项目中的上一份 。
.mostmops.toml[canisters.<name>.check-stable]mops check --fix.most要通过检查,新 migration 的 必须匹配先前部署的 signature,而 必须匹配新 actor body(或为其 stable supertype)。
OldActorNewActor确定性地推导 :你的 应等于 中按字典序排列的前一个文件的 ;如果你的文件是迁移链中的第一个文件,则为 。只有从空 canister 开始的迁移链才使用 ——从 legacy 持久化转换而来的项目从转换前的 stable shape 开始,其现有首个文件已经反映了这一点。
OldActorOldActorsrc/backend/migrations/NewActor{}{}Checklist for Upgrades
升级检查清单
- Decide: implicit (compatible change) vs explicit (migration file)
- At most ONE pending migration file per build. Before creating a file, check — if a migration is already pending, edit it instead of adding a second
src/backend/migrations/ - If explicit: pick a bare UTC-timestamp filename (, no suffix) that sorts after every existing file; do not encode the change in the name
YYYYMMDD_HHMMSS.mo - Set to the
OldActorof the file that precedes yours inNewActor(lex-order), orsrc/backend/migrations/if yours is the first file in a project that started out with a chain. Never from current{}. Never the file's ownmain.mo.NewActor - When the directory is empty (init migration), must list every stable field declared in
NewActor, with a value for eachmain.mo - Inline both (with old types) and
OldActor(with new types) — no project importsNewActor - Implement
public func migration(old : OldActor) : NewActor - Never modify or delete a migration that was already applied; edit (don't duplicate) a pending one
- Do not use preupgrade/postupgrade or for data migration
(with migration = ...) - Iterate on (fast) until it passes — it verifies compilation and upgrade safety
mops check --fix - Run ONCE at the end (slow) to compile the backend and produce the updated IDL bindings
mops build
- 确定使用隐式迁移(兼容变更)还是显式迁移(migration 文件)
- 每次构建最多只能有一个待应用 migration 文件。 创建文件前,检查 ——如果已有待应用 migration,请编辑它,而不是添加第二个
src/backend/migrations/ - 如果使用显式迁移:选择一个仅含 UTC 时间戳的文件名(,无后缀),并确保其排在所有现有文件之后;不要在名称中编码变更内容
YYYYMMDD_HHMMSS.mo - 将 设置为
OldActor中前一个文件(按字典序排列)的src/backend/migrations/;如果你的文件是最初以迁移链启动的项目中的第一个文件,则设置为NewActor。绝不能使用当前{},也不能使用该文件自身的main.moNewActor - 当目录为空时(初始化 migration),必须列出
NewActor中声明的每一个 stable 字段,并为每个字段提供值main.mo - 同时内联 (使用旧类型)和
OldActor(使用新类型)——不得导入项目 moduleNewActor - 实现
public func migration(old : OldActor) : NewActor - 绝不修改或删除已经应用的 migration;编辑待应用 migration,而不是创建重复文件
- 不要使用 preupgrade/postupgrade 或 进行数据迁移
(with migration = ...) - 反复运行 (速度较快)直至通过——它会验证编译和升级安全性
mops check --fix - 最后只运行一次 (速度较慢),以编译后端并生成更新后的 IDL bindings
mops build
Additional References
附加参考
- Migration examples: See examples.md for minimal, self-contained examples (add field, map over collection, add optional field)
- When something does not add up: Load for compatibility diagnostics you cannot explain, write failures on frozen files, projects converted from legacy persistence, and requests to remove the chain. Not needed on the normal path.
troubleshooting-motoko-migrations - General Motoko development: Use for language fundamentals, core library reference, and architecture patterns
writing-motoko - mops tooling: Load for
mops-cliconfiguration,mops.toml,mops check, and toolchain setupmops build - Motoko Docs: Data persistence
- Motoko Docs: Compatibility
- Migration 示例:请参阅 examples.md 中简洁且自包含的示例(添加字段、遍历集合、添加可选字段)
- 当某些情况无法解释时:加载 ,用于排查无法解释的兼容性诊断、冻结文件上的写入失败、从 legacy 持久化转换而来的项目,以及要求移除迁移链的场景。正常流程不需要使用它
troubleshooting-motoko-migrations - Motoko 通用开发:使用 了解语言基础、core library 参考和架构模式
writing-motoko - mops 工具链:加载 以配置
mops-cli、使用mops.toml、mops check和设置工具链mops build - Motoko 文档:数据持久化
- Motoko 文档:兼容性