Why do we need the schema.patch file

When executing diesel migration run diesel connects to the database and expresses the current schema of the database in the schema.rs file. The config for this mechanism is in diesel.toml. You can use diesel print-schema to output the schema manually. Unfortunately Diesel generates type definitions for types we import from Postgis. This results in a double use:

diesel::table! {
    use postgis_diesel::sql_types::Geography; // <-- even though we import using --import-types
    use super::sql_types::Geography;          // <-- this gets generated by Diesel

After generating the schema.rs file Diesel applies the patch file to it.

When to update the schema.patch file

Whenever you get an error message similar to error applying hunk #2 you have to update the schema.patch file. This happens when schema.rs changes in the diff context of the patch file (the lines before and after the change).

How to update the schema.patch file

  1. The following is done relative to the backend directory.

    cd backend
    
  2. Comment out the following line from diesel.toml:

    patch_file = "src/schema.patch"
    

    You can prepend the line with '#'.

  3. Get a clean database with all migrations:

    diesel database reset
    

    You should now have a generated schema.rs in the src directory.

  4. Copy the schema.rs file to schema_tmp.rs.

    cp src/schema.rs src/schema_tmp.rs
    
  5. Make the necessary changes to schema_tmp.rs.

    Look at the existing schema.patch to see what needs to change.

  6. Create a new patch file.

    diff -U6 src/schema.rs src/schema_tmp.rs > src/schema.patch
    
  7. Add patch_file = "src/schema.patch" to the diesel.toml again.

  8. Delete schema_tmp.rs.

From now on the newly generated patch file is used by Diesel.