{"id":16146,"library":"node-pg-migrate","title":"PostgreSQL Database Migration Management Tool","description":"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.","status":"active","version":"8.0.4","language":"javascript","source_language":"en","source_url":"https://github.com/salsita/node-pg-migrate","tags":["javascript","db","database","migrate","migration","migrations","migrator","db-migrate","sql","typescript"],"install":[{"cmd":"npm install node-pg-migrate","lang":"bash","label":"npm"},{"cmd":"yarn add node-pg-migrate","lang":"bash","label":"yarn"},{"cmd":"pnpm add node-pg-migrate","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required for database connection and query execution. This is a peer dependency.","package":"pg","optional":false},{"reason":"TypeScript type definitions for the 'pg' client. Highly recommended for TypeScript projects.","package":"@types/pg","optional":true}],"imports":[{"note":"The primary programmatic interface for running migrations. Modern Node.js projects should use ESM imports. CJS `require` might work for older versions or specific setups but is not the recommended pattern for current releases shipping ESM types.","wrong":"const migrate = require('node-pg-migrate');","symbol":"migrate","correct":"import { migrate } from 'node-pg-migrate';"},{"note":"Used to represent a literal PostgreSQL string that should not be quoted (e.g., `pgm.func('CURRENT_TIMESTAMP')`). It's a value, not just a type.","wrong":"import type { PgLiteral } from 'node-pg-migrate';","symbol":"PgLiteral","correct":"import { PgLiteral } from 'node-pg-migrate';"},{"note":"Core types for defining migration logic. `MigrationBuilder` provides methods for schema manipulation, and `ColumnDefinitions` for shorthand column definitions. These are types, not runtime values.","wrong":"import { MigrationBuilder } from 'node-pg-migrate';","symbol":"MigrationBuilder","correct":"import type { MigrationBuilder, ColumnDefinitions } from 'node-pg-migrate';"}],"quickstart":{"code":"import { migrate } from 'node-pg-migrate';\nimport { Pool } from 'pg';\nimport path from 'path';\nimport 'dotenv/config'; // Make sure to install dotenv if you use it\n\n// --- IMPORTANT: Ensure DATABASE_URL is set in your .env file or environment variables ---\n// Example: DATABASE_URL=postgres://user:password@localhost:5432/testdb\n\nasync function runDatabaseMigrations() {\n  const databaseUrl = process.env.DATABASE_URL ?? 'postgres://user:password@localhost:5432/testdb';\n\n  if (!databaseUrl) {\n    console.error('DATABASE_URL environment variable is not set. Please provide it.');\n    process.exit(1);\n  }\n\n  const pool = new Pool({\n    connectionString: databaseUrl,\n  });\n\n  const migrationsDir = path.resolve(__dirname, 'migrations');\n\n  try {\n    console.log('Starting database migrations...');\n    await migrate({\n      db: pool, // Pass the pg.Pool instance\n      migrationsTable: 'pgmigrations', // Table to track applied migrations\n      dir: migrationsDir, // Directory containing your migration files\n      direction: 'up', // 'up' to apply, 'down' to revert\n      count: Infinity, // Apply all pending migrations\n      createShorthands: true, // Automatically create shorthand definitions\n      // verbose: true, // Uncomment for detailed logging\n      log: (message: string) => console.log(`[node-pg-migrate] ${message}`),\n      noLock: false, // Use advisory locks to prevent concurrent migrations\n      dryRun: false // Set to true to preview changes without applying\n    });\n    console.log('Database migrations completed successfully.');\n  } catch (error) {\n    console.error('Database migration failed:', error);\n    process.exit(1);\n  } finally {\n    await pool.end();\n  }\n}\n\nrunDatabaseMigrations();\n\n// To run this:\n// 1. npm install node-pg-migrate pg dotenv\n// 2. Create a 'migrations' directory.\n// 3. Create a migration file, e.g., 'migrations/001_initial_schema.ts':\n//    import type { MigrationBuilder, ColumnDefinitions } from 'node-pg-migrate';\n//    export async function up(pgm: MigrationBuilder): Promise<void> {\n//      pgm.createTable('users', { id: 'id', name: { type: 'varchar(100)', notNull: true } });\n//    }\n//    export async function down(pgm: MigrationBuilder): Promise<void> {\n//      pgm.dropTable('users');\n//    }\n// 4. Configure DATABASE_URL in a .env file.\n// 5. Run with `npx ts-node your-migration-script.ts` (assuming ts-node is installed)","lang":"typescript","description":"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."},"warnings":[{"fix":"Review the official v9.x release notes and documentation once available. Plan for code refactoring and thorough testing when migrating from v8.x.","message":"Version 9.x (currently in alpha) will introduce significant breaking changes, including revised migration loading strategies and potential adjustments to the programmatic API. Users upgrading from v8.x should carefully consult the v9 release notes and migration guides to understand necessary code adaptations.","severity":"breaking","affected_versions":">=9.0.0-alpha.1"},{"fix":"Ensure your `pg` dependency is explicitly within the range `>=4.3.0 <9.0.0`. For `pg` v9.x compatibility, you will likely need to upgrade to `node-pg-migrate` v9.x when it stabilizes.","message":"node-pg-migrate v8.x has a strict peer dependency on `pg` version `>=4.3.0 <9.0.0`. Using `pg` v9.x or newer with `node-pg-migrate` v8.x will lead to compatibility issues, potentially causing errors or preventing migrations from executing.","severity":"gotcha","affected_versions":"8.x"},{"fix":"Upgrade your Node.js runtime to version 20.11.0 or newer to meet the engine requirements.","message":"Version 8.x of node-pg-migrate requires Node.js `v20.11.0` or higher. Running on older Node.js versions will result in errors due to unsupported syntax or missing runtime features.","severity":"gotcha","affected_versions":">=8.0.0"},{"fix":"Immediately upgrade node-pg-migrate to version 8.0.4 or newer to incorporate the security patches.","message":"Version 8.0.4 includes a critical security fix related to the `glob` dependency. Prior versions may be vulnerable to specific path traversal or denial-of-service issues.","severity":"breaking","affected_versions":"<8.0.4"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"fix":"Run `npm install node-pg-migrate pg` or `yarn add node-pg-migrate pg` to install the package and its peer dependency.","cause":"The 'node-pg-migrate' package is not installed or not accessible in the current project environment.","error":"Error: Cannot find module 'node-pg-migrate'"},{"fix":"Verify that your PostgreSQL server is operational and accessible. Double-check your `DATABASE_URL` environment variable or connection configuration for accuracy, including host, port, username, and password.","cause":"The PostgreSQL database server is either not running, or the connection string/details (host, port, credentials) are incorrect.","error":"Error: connect ECONNREFUSED"},{"fix":"Refactor your imports to use ES module syntax (e.g., `import { migrate } from 'node-pg-migrate';`). If using TypeScript, ensure your `tsconfig.json` `module` and `moduleResolution` settings are appropriate for ESM.","cause":"You are attempting to use CommonJS `require()` syntax in an ES module (`.mjs` or `\"type\": \"module\"` in `package.json`) for a package that is primarily designed for ESM or ships ESM types.","error":"ReferenceError: require is not defined in ES module scope"},{"fix":"Use a runtime TypeScript executor like `ts-node` (`npx ts-node your-script.ts`) or `tsx` (`npx tsx your-script.ts`). Alternatively, compile your TypeScript migration files to JavaScript before running.","cause":"Node.js cannot directly execute TypeScript migration files (`.ts`) without a transpiler or loader in place (e.g., `ts-node`, `tsx`).","error":"TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension \".ts\" for ..."}],"ecosystem":"npm"}