This repository provides an example of a PostgreSQL schema migration using pgroll, a tool designed for zero-downtime migrations.
Before running the commands, you must configure the environment variables to allow pgroll to connect to the database.
Export the following variables to your terminal or add them to a .env file.
export PGROLL_PG_URL="postgresql://<your_user>:<your_password>@<your_host>:<your_port>/<your_db>?sslmode=<disable|require>"
export PGROLL_SCHEMA="<your_schema>"If you prefer managing configurations via a .env file, you can load them with the following command.
export $(grep -v '^#' .env | xargs)For details on connection string syntax, refer to the Official CLI Documentation.
Required only the first time to prepare the database for pgroll.
pgroll initFor the simple migrations that do not require an intermediate testing phase, use the --complete flag. This performs the "expand" and "contract" phases in a single step.
pgroll start postgres-migrations/00_create_demo_schema.yaml --completepgroll start postgres-migrations/01_create_users_table.yaml --completepgroll start postgres-migrations/02_add_past_due_column.yaml --complete
pgroll start postgres-migrations/03_add_canceled_column.yaml --completeIt is also possible to migrate all configurations in the migrations directory with a single command.
pgroll migrate --completeTo carry out a realistic test, it is necessary to fill the database with a few million records.
You can run the SQL script populate.sql under
postgres-scripts directory.
For the critical changes, follow the two-step flow to ensure application compatibility:
This creates the new version of the schema while keeping the old one active.
pgroll start postgres-migrations/04_add_status_column.yamlCheck the pgroll status.
pgroll statuspgroll complete # If everything is working correctly
# OR
pgroll rollback # If you encounter issuesOnce migration is complete you can drop safely unused columns.
pgroll start postgres-migrations/05_drop_columns.yaml --complete