Postgres-schema-migrations is a JavaScript/TypeScript library for managing database schema changes in PostgreSQL. It is a fork of `postgres-migrations` that specifically adds support for schema namespaces, allowing separate migrations to be tracked per schema, which is beneficial for multi-tenant applications or reusing database code. Currently at version 7.0.2, this library is actively maintained. It mandates SQL files for migration definitions, ordered numerically, and deliberately omits 'down' migrations, advocating for 'rolling forward' with new migrations to reverse changes. A key differentiator is its emphasis on atomic transactions for each migration and hash-based checks to ensure migration immutability, preventing accidental changes to already-applied migrations. It supports Node.js 10.17.0+ and PostgreSQL 9.4+.
npm install postgres-schema-migrationsVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to apply database migrations using a `pg` client, showing both default (public) and namespaced schema migrations. It highlights connection management and error handling.
Plan for 'rolling forward' changes by writing new SQL migration files that negate or modify previous changes, rather than attempting to roll back.
NEVER alter migration files that have already been applied to any environment. If a change is needed, create a new, subsequent migration file.
Use the `loadMigrationFiles` function or the `pg-validate-migrations` bin script during CI/CD to detect conflicts early. Establish clear team guidelines for migration file naming and sequencing to avoid overlaps.
Always explicitly set `ensureDatabaseExists: true` if you want the library to create the database if it doesn't exist. Ensure `defaultDatabase` is set correctly if not using 'postgres' as the default administrative database.
For large tables or high-traffic systems, use `CREATE INDEX CONCURRENTLY` and ensure your migration is *not* wrapped in a transaction if this is used (the library allows disabling transactions per-migration with `-- postgres-migrations disable-transaction`). For `ALTER TABLE` operations, follow best practices for zero-downtime migrations such as multi-step processes for adding `NOT NULL` constraints or dropping columns.
Never modify migration files after they have been run in any environment. If a change is needed, create a new migration file with a higher sequence number to apply the correction or new schema change.
Set `ensureDatabaseExists: true` in your database configuration object passed to `migrate` if you want the library to create the database automatically. Alternatively, manually create the database before running migrations.
Rename one of the conflicting migration files to have a unique, higher sequential number. For example, if `5_add-table.sql` exists, rename `5_add-new-feature.sql` to `6_add-new-feature.sql`.