@ravshansbox/pg-migrate
v0.12.1
Published
PostgreSQL Migration tool for NodeJS
Downloads
1,263
Maintainers
Readme
pg-migrate
A simple, typesafe PostgreSQL migration tool for Node.js applications.
Features
- Supports up and down migrations
- Transaction-based migration application
- Synchronize to handle dangling migrations
- Simple command-line interface
- TypeScript support out of the box
Installation
npm install @ravshansbox/pg-migrateUsage
Environment Variables
Configure your database connection:
DATABASE_URL=postgres://username:password@host:port/databaseIf not provided, it defaults to postgres://postgres:postgres@localhost:5432/postgres.
Creating Migrations
Create a new migration file:
pg-migrate make 001_create-users-tableThis will create a file in the migrations directory with the following format:
-- Up
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
email TEXT UNIQUE NOT NULL
);
-- Down
DROP TABLE users;Running Migrations
Synchronize the database with your migration files(preferred command):
pg-migrate syncApply all pending migrations(if you do not want automatic reversions):
pg-migrate upRevert all applied migrations:
pg-migrate downHow it Works
pg-migrate keeps track of applied migrations in a _migrations table in your database. When you run migrations, it:
- Checks which migrations have already been applied
- Wraps new migrations in a transaction
- Applies migrations in alphanumeric order
- Records successful migrations along with their "down" SQL for potential rollback
Migration File Format
Migration files should follow this structure:
-- Up
-- Your SQL to apply the migration
-- Down
-- Your SQL to reverse the migrationThe parser looks for these exact markers to separate up and down migrations.
API Usage
You can also use pg-migrate programmatically in your code. All public functions require a pg.Client instance, giving you full control over the connection lifecycle:
import pg from 'pg'
import { migrateUp, migrateDown, migrateSync } from '@ravshansbox/pg-migrate'
const client = new pg.Client({ connectionString: 'postgres://user:pass@host:5432/db' })
await client.connect()
try {
// Apply pending migrations
await migrateUp(client)
// Revert migrations
await migrateDown(client)
// Synchronize migrations (reverts dangling, then applies pending)
await migrateSync(client)
} finally {
await client.end()
}License
MIT
