Postgres Migrations

5.3.0 · active · verified Wed Apr 22

The `postgres-migrations` package provides a robust database migration solution for PostgreSQL, directly inspired by Stack Overflow's deployment methodology. Currently at version 5.3.0, it offers a stable and opinionated approach to managing database schema changes. Key differentiators include its strict sequential SQL file-based ordering, which explicitly avoids timestamp-based naming to ensure consistent execution order across all environments. The library deliberately eschews 'down' migrations, advocating for a 'roll forward' philosophy where issues are addressed by applying new incremental migrations. It enforces database integrity by performing hash checks on previously applied migration files, preventing accidental or unauthorized modifications. The package maintains a hidden `migrations` table to track applied scripts and requires Node.js 10.17.0+ and PostgreSQL 9.4+.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to apply migrations using an existing `pg.Client` instance, ensuring proper connection handling and error reporting. It uses environment variables for database credentials.

import { migrate } from 'postgres-migrations';
import { Client } from 'pg';
import path from 'path';

async function runMigrations() {
  const dbConfig = {
    database: process.env.DB_NAME ?? 'your_database',
    user: process.env.DB_USER ?? 'postgres',
    password: process.env.DB_PASSWORD ?? 'password',
    host: process.env.DB_HOST ?? 'localhost',
    port: parseInt(process.env.DB_PORT ?? '5432', 10),
    // ensureDatabaseExists: true // Uncomment if you want the library to create the database if it doesn't exist
  };

  const client = new Client(dbConfig);
  await client.connect();

  try {
    console.log('Starting database migrations...');
    const migrationsPath = path.resolve(__dirname, 'migrations');
    await migrate({ client }, migrationsPath);
    console.log('Database migrations completed successfully.');
  } catch (error) {
    console.error('Migration failed:', error);
    process.exit(1);
  } finally {
    await client.end();
  }
}

// Example migrations directory structure:
// my-project/
// ├── src/
// │   └── index.ts (or .js)
// └── migrations/
//     ├── 1_create_users_table.sql
//     └── 2_add_posts_table.sql

runMigrations();

view raw JSON →