Schema 演进
Schema 演进允许数据结构在演进过程中仍与历史序列化数据保持兼容。Fory Go 通过兼容模式提供该能力。
启用兼容模式
Enable compatible mode when creating a Fory instance:
f := fory.New(fory.WithCompatible(true))
工作机制
Without Compatible Mode (Default)
- Compact serialization without metadata
- Struct hash is checked during deserialization
- Any schema change causes
ErrKindHashMismatch
With Compatible Mode
- Type metadata is written to serialized data
- Supports adding, removing, and reordering fields
- Enables forward and backward compatibility
支持的 Schema 变更
新增字段
New fields can be added; they receive zero values when deserializing old data:
// Version 1
type UserV1 struct {
ID int64
Name string
}
// Version 2 (added Email)
type UserV2 struct {
ID int64
Name string
Email string // New field
}
f := fory.New(fory.WithCompatible(true))
f.RegisterStruct(UserV1{}, 1)
// Serialize with V1
userV1 := &UserV1{ID: 1, Name: "Alice"}
data, _ := f.Serialize(userV1)
// Deserialize with V2
f2 := fory.New(fory.WithCompatible(true))
f2.RegisterStruct(UserV2{}, 1)
var userV2 UserV2
f2.Deserialize(data, &userV2)
// userV2.Email = "" (zero value)
删除字段
Removed fields are skipped during deserialization:
// Version 1
type ConfigV1 struct {
Host string
Port int32
Timeout int64
Debug bool // Will be removed
}
// Version 2 (removed Debug)
type ConfigV2 struct {
Host string
Port int32
Timeout int64
// Debug field removed
}
f := fory.New(fory.WithCompatible(true))
f.RegisterStruct(ConfigV1{}, 1)
// Serialize with V1
config := &ConfigV1{Host: "localhost", Port: 8080, Timeout: 30, Debug: true}
data, _ := f.Serialize(config)
// Deserialize with V2
f2 := fory.New(fory.WithCompatible(true))
f2.RegisterStruct(ConfigV2{}, 1)
var configV2 ConfigV2
f2.Deserialize(data, &configV2)
// Debug field data is skipped