# Schema migration

> agdb example: migrating stored data to a new schema inside a single transaction

## What it shows

The example stores 100 users with an old schema (`name`, `status` as a string and `age`) and migrates them to a new one (`db_id`, `name` and `status` as an enum stored as a number). The whole migration runs in one mutable transaction, so it either fully succeeds or leaves the data untouched.

## Run it

```bash
cargo run -p agdb --example schema_migration
```

## Converting values in both directions

The trick of the migration is in the conversions of the new `UserStatus` enum. Reading accepts both the old string values and the new numbers, while writing always stores numbers:

```rs
impl TryFrom<DbValue> for UserStatus {
    type Error = DbError;

    fn try_from(value: DbValue) -> Result<Self, Self::Error> {
        match value.to_string().as_str() {
            "active" | "0" => Ok(Self::Active),
            "inactive" | "1" => Ok(Self::Inactive),
            "banned" | "2" => Ok(Self::Banned),
            _ => Err(DbError::db(
                agdb::DbErrorType::TypeError,
                "Invalid user status",
            )),
        }
    }
}
impl From<UserStatus> for DbValue {
    fn from(value: UserStatus) -> Self {
        match value {
            UserStatus::Active => 0_u64.into(),
            UserStatus::Inactive => 1_u64.into(),
            UserStatus::Banned => 2_u64.into(),
        }
    }
}
```

## The migration

Inside the transaction the obsolete `age` property is removed from all users, the users are loaded with the new schema (the conversion above accepts the old strings) and inserted back, which overwrites the `status` values with numbers:

```rs
db.transaction_mut(|t| {
    // First remove the "age" property from all the users.
    t.exec_mut(
        QueryBuilder::remove()
            .values("age")
            .ids(QueryBuilder::search().from("users").query())
            .query(),
    )?;

    let users: Vec<UserDb2> = t
        .exec(
            QueryBuilder::select()
                .search()
                .from("users")
                .where_()
                .neighbor()
                .query(),
        )?
        .try_into()?;

    t.exec_mut(QueryBuilder::insert().elements(&users).query())

    // NOTE: When migrating huge amount of data it would be better to do it in batches using
    // the `limit` and `offset` values in the search query.
})?;
```

## Learn more

- [Transactions](/docs/references/queries#transactions) in the queries reference.
- [Remove values](/docs/references/queries#remove-values) and [insert values](/docs/references/queries#insert-values).
- [DbType](/docs/references/queries#dbtype) - how user types map to stored values.

<style>

html pre.shiki code .sbgvK, html code.shiki .sbgvK{--shiki-light:#E2931D;--shiki-default:#6F42C1;--shiki-dark:#B392F0}html pre.shiki code .s_sjI, html code.shiki .s_sjI{--shiki-light:#91B859;--shiki-default:#032F62;--shiki-dark:#9ECBFF}html pre.shiki code .stzsN, html code.shiki .stzsN{--shiki-light:#91B859;--shiki-default:#005CC5;--shiki-dark:#79B8FF}html .light .shiki span {color: var(--shiki-light);background: var(--shiki-light-bg);font-style: var(--shiki-light-font-style);font-weight: var(--shiki-light-font-weight);text-decoration: var(--shiki-light-text-decoration);}html.light .shiki span {color: var(--shiki-light);background: var(--shiki-light-bg);font-style: var(--shiki-light-font-style);font-weight: var(--shiki-light-font-weight);text-decoration: var(--shiki-light-text-decoration);}html .default .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .dark .shiki span {color: var(--shiki-dark);background: var(--shiki-dark-bg);font-style: var(--shiki-dark-font-style);font-weight: var(--shiki-dark-font-weight);text-decoration: var(--shiki-dark-text-decoration);}html.dark .shiki span {color: var(--shiki-dark);background: var(--shiki-dark-bg);font-style: var(--shiki-dark-font-style);font-weight: var(--shiki-dark-font-weight);text-decoration: var(--shiki-dark-text-decoration);}html pre.shiki code .sw1J6, html code.shiki .sw1J6{--shiki-light:#F76D47;--shiki-default:#D73A49;--shiki-dark:#F97583}html pre.shiki code .sP7_E, html code.shiki .sP7_E{--shiki-light:#39ADB5;--shiki-default:#24292E;--shiki-dark:#E1E4E8}html pre.shiki code .sVHd0, html code.shiki .sVHd0{--shiki-light:#39ADB5;--shiki-light-font-style:italic;--shiki-default:#D73A49;--shiki-default-font-style:inherit;--shiki-dark:#F97583;--shiki-dark-font-style:inherit}html pre.shiki code .sbsja, html code.shiki .sbsja{--shiki-light:#9C3EDA;--shiki-default:#D73A49;--shiki-dark:#F97583}html pre.shiki code .smGrS, html code.shiki .smGrS{--shiki-light:#39ADB5;--shiki-default:#D73A49;--shiki-dark:#F97583}html pre.shiki code .sGLFI, html code.shiki .sGLFI{--shiki-light:#6182B8;--shiki-default:#6F42C1;--shiki-dark:#B392F0}html pre.shiki code .su5hD, html code.shiki .su5hD{--shiki-light:#90A4AE;--shiki-default:#24292E;--shiki-dark:#E1E4E8}html pre.shiki code .s_hVV, html code.shiki .s_hVV{--shiki-light:#90A4AE;--shiki-default:#005CC5;--shiki-dark:#79B8FF}html pre.shiki code .sjJ54, html code.shiki .sjJ54{--shiki-light:#39ADB5;--shiki-default:#032F62;--shiki-dark:#9ECBFF}html pre.shiki code .srdBf, html code.shiki .srdBf{--shiki-light:#F76D47;--shiki-default:#005CC5;--shiki-dark:#79B8FF}html pre.shiki code .sutJx, html code.shiki .sutJx{--shiki-light:#90A4AE;--shiki-light-font-style:italic;--shiki-default:#6A737D;--shiki-default-font-style:inherit;--shiki-dark:#6A737D;--shiki-dark-font-style:inherit}

</style>

---

- [View source](https://github.com/agnesoft/agdb/blob/main/agdb/examples/schema_migration.rs)
