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
-
The following is done relative to the
backend
directory.cd backend
-
Comment out the following line from
diesel.toml
:patch_file = "src/schema.patch"
You can prepend the line with '#'.
-
Get a clean database with all migrations:
diesel database reset
You should now have a generated
schema.rs
in thesrc
directory. -
Copy the
schema.rs
file toschema_tmp.rs
.cp src/schema.rs src/schema_tmp.rs
-
Make the necessary changes to
schema_tmp.rs
.Look at the existing
schema.patch
to see what needs to change. -
Create a new patch file.
diff -U6 src/schema.rs src/schema_tmp.rs > src/schema.patch
Note: Make sure the correct encoding (UTF-8) and line break type (LF) is used. This is probably not an issue when working with Linux but in Windows the defaults seem to be UTF-16 and CRLF so be aware when using different operating systems.
-
Add
patch_file = "src/schema.patch"
to thediesel.toml
again. -
Delete
schema_tmp.rs
.
From now on the newly generated patch file is used by Diesel.