|
| 1 | +# SQLPage migrations |
| 2 | + |
| 3 | +SQLPage migrations are SQL scripts that you can use to create or update the database schema. |
| 4 | +They are entirely optional: you can use SQLPage without them, and manage the database schema yourself with other tools. |
| 5 | + |
| 6 | +## Creating a migration |
| 7 | + |
| 8 | +To create a migration, create a file in the `sqlpage/migrations` directory with the following name: |
| 9 | + |
| 10 | +``` |
| 11 | +<version>_<name>.sql |
| 12 | +``` |
| 13 | + |
| 14 | +Where `<version>` is a number that represents the version of the migration, and `<name>` is a name for the migration. |
| 15 | +For example, `001_initial.sql` or `002_add_users.sql`. |
| 16 | + |
| 17 | +When you need to update the database schema, always create a **new** migration file with a new version number |
| 18 | +that is greater than the previous one. |
| 19 | +Use commands like `ALTER TABLE` to update the schema declaratively instead of modifying the existing `CREATE TABLE` |
| 20 | +statements. |
| 21 | + |
| 22 | +If you try to edit an existing migration, SQLPage will not run it again, will detect |
| 23 | + |
| 24 | +## Running migrations |
| 25 | + |
| 26 | +Migrations that need to be applied are run automatically when SQLPage starts. |
| 27 | +You need to restart SQLPage each time you create a new migration. |
| 28 | + |
| 29 | +## How does it work? |
| 30 | + |
| 31 | +SQLPage keeps track of the migrations that have been applied in a table called `_sqlx_migrations`. |
| 32 | +This table is created automatically when SQLPage starts for the first time, if you create migration files. |
| 33 | +If you don't create any migration files, SQLPage will never touch the database schema on its own. |
| 34 | + |
| 35 | +When SQLPage starts, it checks the `_sqlx_migrations` table to see which migrations have been applied. |
| 36 | +It checks the `sqlpage/migrations` directory to see which migrations are available. |
| 37 | +If the checksum of a migration file is different from the checksum of the migration that has been applied, |
| 38 | +SQLPage will return an error and refuse to start. |
| 39 | +If you end up in this situation, you can remove the `_sqlx_migrations` table: all your old migrations will be reapplied, and SQLPage will start again. |
0 commit comments