Introduction
For development purposes, you already know theUpdate DB workflow from the Schema Designer. Once your app is running in production you will at some point need to make changes to your database schema. With migrations, you can evolve your production database schema by writing short SQL statements to make the necessary changes.
In IHP a migration file is a plain SQL file consisting of ALTER TABLE and other SQL statements that patch the database. They are stored in Application/Migration and are named by a timestamp and an optional description.
Here’s how a directory structure with a few migrations can look like:
Generating a Migration
Open the Code Generator
Open the Code Generator and click
Migration. You need to enter an optional description, e.g. Create Posts Table. The description will be sluggified to create-posts-table when generating the migration file.Schema.sql into this migration:
Running Migrations
IHP provides a shell commandmigrate that runs all migrations that haven’t be executed yet. A table schema_migrations is used to keep track of which migrations already have been run. The table will be automatically created by the migrate tool.
To test your migrations locally, first add ihp-migrate to your flake.nix if you haven’t already:
DATABASE_URL environment variable:
nix run .#migrate.
Skipping Old Migrations
You can set theMINIMUM_REVISION env variable when running migrate to ignore migration revisions older than the specified unix timestamp:
MINIMUM_REVISION is typically the unix timestamp of the time when the database was initially created.
Custom Migration Directory
In production when running the migrations binary it is sometimes convenient to have all your Migrations in a non-standard place: e.g. if you need to push migrations onto production server without rebuilding the application. There is an Environment variableIHP_MIGRATION_DIR to accomplish this.