Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for adding new fields to previously serialized structs #299

Open
yanliu38 opened this issue Jun 2, 2024 · 2 comments
Open

Support for adding new fields to previously serialized structs #299

yanliu38 opened this issue Jun 2, 2024 · 2 comments

Comments

@yanliu38
Copy link

yanliu38 commented Jun 2, 2024

Hi there,

We have some existing serialized data of something like

use borsh::{BorshDeserialize, BorshSerialize};

#[derive(BorshSerialize, BorshDeserialize)]
struct MyStruct {
    field1: u32,
    field2: String,
}

We would now like to add a new field to the existing struct to have something like:

use borsh::{BorshDeserialize, BorshSerialize};

#[derive(BorshSerialize, BorshDeserialize)]
struct MyStruct {
    field1: u32,
    field2: String,
    field3: Option<u64>,
}

However, when deserializing existing data with the new MyStruct, the following error is returned:

Custom { kind: InvalidData, error: "Unexpected length of input" }

What is the recommended way to add fields to an existing struct, that already has serialized data?

@yanliu38
Copy link
Author

yanliu38 commented Jun 2, 2024

Seems to be related: #114

@frol
Copy link
Collaborator

frol commented Jun 4, 2024

Borsh does not include the schema inside the serialized data, so you should plan your upgradability accordingly. If you start from scratch, you have two paths:

  1. keep versioned data structured using enum (enum MyStruct { V1(MyStructV1) }), which will add a one byte tag as part of the borsh serialization for enums, here is an example
  2. plan to keep the data always at the latest state and as such, implement migration logic that would read all the old data using old structs, convert those into the new structs, and write it over using, here is an example

If you already have the data serialized with the old MyStruct, you can follow (2) and consider to implement (1) for seamless operation going forward.

Would you like to contribute a README/docs for this topic? I would be happy to review a PR

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants