BE migration (with Diesel)
This blog will show you steps you need to take to write a migration for database working with Diesel (ORM we currently use)
1. Design
Before you start actually writing/executing the migration, think about what is the purpose of this migration. Is it actually necessary? Will it break a bunch of related stuffs? Could it be improved somehow. Your product is only as good as the design.
2. Writing SQL migration file
The first thing you need to do for the actual implementation of the migration is to write migration files in sql language.
All the migration files are stored in folder backend/migrations
. Take a look at the existing folders and files to get a better idea of what is gonna happen. Basically, one migration contains 2 files, up.sql
and down.sql
. The former does all the changes you have intended to do to the database while the latter rolls back all the changes (undo) them.
You don’t have to manually create the folder and files. Here’s let’s reference the Diesel website:
https://diesel.rs/guides/getting-started
You only need to type diesel migration generate <name>
into your command shell and Diesel will create the new migration folder for you.
After writing your up and down sql files. Run diesel migration run
to apply the changes. This command would only execute the migrations that have never been applied to the database (I thk so). For rolling back run diesel migration revert
. The command diesel migration redo
as its name suggests, rolls back your change and then redoes it.
3. Schema & Model
Diesel being the Diesel, it doesn’t push the updates to database to our schema file. Thus, you’d need to manually change backend/server/src/database/schema.rs
. To let the backend code know the newly updated database schema.
If your migration involves change in any data structure (which likely does). Update the data structure in the backend code. Either in backend/server/src/database/models.rs
or wherever else it is.
4. Rocket
please look into backend/server/src/bin.rs
if your changes involve adding new routes.
Just make sure the code compiles then it would most likely be fine.