Examples
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
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:
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:
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 in the queries reference.
- Remove values and insert values.
- DbType - how user types map to stored values.