Skip to content

Commit 357edde

Browse files
authored
fix(cli)!: ensure env vars are set before migrating (#1222)
1 parent 93e398c commit 357edde

File tree

3 files changed

+21
-2
lines changed

3 files changed

+21
-2
lines changed

.github/workflows/postgres-test.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -493,6 +493,7 @@ jobs:
493493
- name: Integration Test
494494
run: pnpm run migrate up -m test/migrations && pnpm run migrate down 0 -m test/migrations --timestamps
495495
env:
496+
PGHOST: localhost
496497
PGUSER: ubuntu
497498
PGPASSWORD: 123456abcdefghABCDEFGH~\`\!@#$%^\&*-_=+{}[]\(\)\<\>,.\;:\"\'?\|/\\
498499
PGDATABASE: integration_test

bin/node-pg-migrate.ts

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -528,9 +528,12 @@ if (action === 'create') {
528528
if (!DB_CONNECTION) {
529529
const cp = new ConnectionParameters();
530530

531-
if (!cp.host && !cp.port && !cp.database) {
531+
if (
532+
!process.env[argv[databaseUrlVarArg]] &&
533+
(!process.env.PGHOST || !cp.user || !cp.database)
534+
) {
532535
console.error(
533-
`The $${argv[databaseUrlVarArg]} environment variable is not set.`
536+
`The ${argv[databaseUrlVarArg]} environment variable is not set or incomplete connection parameters are provided.`
534537
);
535538
process.exit(1);
536539
}

docs/src/faq/troubleshooting.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,3 +45,18 @@ transaction.
4545
E.g., if it is created in previous migration.
4646
You need to run specific migration outside transaction
4747
(`pgm.noTransaction`).
48+
49+
## Environment Variables
50+
51+
`node-pg-migrate` relies on the `node-postgres` library for database connections. The following [PostgreSQL Environment Variables](https://www.postgresql.org/docs/9.1/libpq-envars.html) may be used:
52+
53+
- `DATABASE_URL`: The URL of the database to connect to.
54+
- `PGHOST`: The host of the PostgreSQL server.
55+
- `PGUSER`: The username for the PostgreSQL server.
56+
- `PGPASSWORD`: The password for the PostgreSQL server.
57+
- `PGDATABASE`: The name of the database to connect to.
58+
59+
For up-to-date default values from `node-postgres`, [see](https://github.com/brianc/node-postgres/blob/master/packages/pg/lib/defaults.js).
60+
61+
Starting from version 8.0, `node-pg-migrate` will refuse to run migrations if `DATABASE_URL` is not set, or if the required environment variables (`PGHOST`, `PGUSER`, `PGDATABASE`) are missing. This check ensures that migrations do not run with default or unintended connection parameters.
62+
This behavior is based on the `node-postgres` library, which synthesizes some default connection parameters. For example, `pg` sets the `host` to `localhost` and the `port` to `5432` if they are missing.

0 commit comments

Comments
 (0)