Skip to content

node-pg-migrateDatabase migrations, made for PostgreSQL

Write migrations in JavaScript, TypeScript or SQL, preview the exact SQL, and roll back without writing every down migration by hand.

npm add pg && npm add -D node-pg-migrate

Code in, SQL out ​

Write migrations in TypeScript, JavaScript or plain SQL. In TypeScript and JavaScript every pgm call compiles to SQL: the second panel is exactly what node-pg-migrate up --pretty runs, plus the down it infers because the migration leaves one out. Hover the TypeScript code to see its types.

ts
import type { 
MigrationBuilder
} from 'node-pg-migrate';
export async function
up
(
pgm
:
MigrationBuilder
):
Promise
<void> {
pgm
.
createTable
('users', {
id
: 'id',
email
: {
type
: 'text',
notNull
: true,
unique
: true },
createdAt
: {
type
: 'timestamptz',
notNull
: true,
default
:
pgm
.
func
('now()'),
}, });
pgm
.
createIndex
('users', 'createdAt');
}
js
export const up = (pgm) => {
  pgm.createTable('users', {
    id: 'id',
    email: { type: 'text', notNull: true, unique: true },
    createdAt: {
      type: 'timestamptz',
      notNull: true,
      default: pgm.func('now()'),
    },
  });
  pgm.createIndex('users', 'createdAt');
};
sql
-- Up Migration
CREATE TABLE "users" (
  "id" serial PRIMARY KEY,
  "email" text UNIQUE NOT NULL,
  "createdAt" timestamptz DEFAULT now() NOT NULL
);
CREATE INDEX "users_createdAt_index" ON "users" ("createdAt");

-- Down Migration
DROP INDEX "users_createdAt_index";
DROP TABLE "users";
sql
CREATE TABLE "users" (
  "id" serial PRIMARY KEY,
  "email" text UNIQUE NOT NULL,
  "createdAt" timestamptz DEFAULT now() NOT NULL
);
CREATE INDEX "users_createdAt_index" ON "users" ("createdAt");
sql
DROP INDEX "users_createdAt_index";
DROP TABLE "users";

Built for Postgres, all of it ​

node-pg-migrate only targets PostgreSQL, so it can cover what Postgres actually has. Each of these has its own operations in the pgm API: