PostgreSQL Database Migration Management Tool

8.0.4 · active · verified Tue Apr 21

node-pg-migrate is a robust and feature-rich PostgreSQL database migration management tool designed for Node.js environments. It empowers developers to manage schema changes through JavaScript or TypeScript migration files, offering precise control over `up` and `down` operations for evolving database schemas. The current stable version is 8.0.4, with active development proceeding on the v9.0.0 alpha series, indicating a future major release that will introduce significant enhancements and breaking changes. The project generally maintains a consistent release cadence for minor and patch versions, while major updates are developed over a longer period. Key advantages include its strong TypeScript support, a flexible and extensible migration file structure, and a comprehensive command-line interface, all contributing to streamlined and reliable database schema evolution. It integrates natively with the `pg` client library for database interactions.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to programmatically run `node-pg-migrate` to apply all pending database migrations using a `pg.Pool` instance and environment variables for connection.

import { migrate } from 'node-pg-migrate';
import { Pool } from 'pg';
import path from 'path';
import 'dotenv/config'; // Make sure to install dotenv if you use it

// --- IMPORTANT: Ensure DATABASE_URL is set in your .env file or environment variables ---
// Example: DATABASE_URL=postgres://user:password@localhost:5432/testdb

async function runDatabaseMigrations() {
  const databaseUrl = process.env.DATABASE_URL ?? 'postgres://user:password@localhost:5432/testdb';

  if (!databaseUrl) {
    console.error('DATABASE_URL environment variable is not set. Please provide it.');
    process.exit(1);
  }

  const pool = new Pool({
    connectionString: databaseUrl,
  });

  const migrationsDir = path.resolve(__dirname, 'migrations');

  try {
    console.log('Starting database migrations...');
    await migrate({
      db: pool, // Pass the pg.Pool instance
      migrationsTable: 'pgmigrations', // Table to track applied migrations
      dir: migrationsDir, // Directory containing your migration files
      direction: 'up', // 'up' to apply, 'down' to revert
      count: Infinity, // Apply all pending migrations
      createShorthands: true, // Automatically create shorthand definitions
      // verbose: true, // Uncomment for detailed logging
      log: (message: string) => console.log(`[node-pg-migrate] ${message}`),
      noLock: false, // Use advisory locks to prevent concurrent migrations
      dryRun: false // Set to true to preview changes without applying
    });
    console.log('Database migrations completed successfully.');
  } catch (error) {
    console.error('Database migration failed:', error);
    process.exit(1);
  } finally {
    await pool.end();
  }
}

runDatabaseMigrations();

// To run this:
// 1. npm install node-pg-migrate pg dotenv
// 2. Create a 'migrations' directory.
// 3. Create a migration file, e.g., 'migrations/001_initial_schema.ts':
//    import type { MigrationBuilder, ColumnDefinitions } from 'node-pg-migrate';
//    export async function up(pgm: MigrationBuilder): Promise<void> {
//      pgm.createTable('users', { id: 'id', name: { type: 'varchar(100)', notNull: true } });
//    }
//    export async function down(pgm: MigrationBuilder): Promise<void> {
//      pgm.dropTable('users');
//    }
// 4. Configure DATABASE_URL in a .env file.
// 5. Run with `npx ts-node your-migration-script.ts` (assuming ts-node is installed)

view raw JSON →