Skip to content

API Reference

Vivek edited this page Jul 14, 2026 · 2 revisions

API Reference

Complete API for pg-migration-engine.


Installation

npm install pg-migration-engine pg

Main Class: PgMigrationEngine

import { PgMigrationEngine } from 'pg-migration-engine';
import pg from 'pg';

const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
const engine = new PgMigrationEngine();

Methods

introspect(pool)

Capture current database schema.

const snapshot = await engine.introspect(pool);
Parameter Type Description
pool pg.Pool PostgreSQL connection pool

Returns: Promise<SchemaSnapshot>

interface SchemaSnapshot {
  version: number;           // PG version (10-18)
  tables: Map<string, Table>;
  views: Map<string, View>;
  indexes: Map<string, Index>;
  constraints: Map<string, Constraint>;
  sequences: Map<string, Sequence>;
  functions: Map<string, PostgresFunction>;
  procedures: Map<string, Procedure>;
  triggers: Map<string, Trigger>;
  policies: Map<string, Policy>;
  enums: Map<string, EnumType>;
  composites: Map<string, CompositeType>;
  domains: Map<string, DomainType>;
  ranges: Map<string, RangeType>;
  schemas: Map<string, Schema>;
  extensions: Map<string, Extension>;
  statistics: Map<string, Statistics>;
  collations: Map<string, Collation>;
  casts: Cast[];
  operators: Operator[];
  opClasses: OpClass[];
  opFamilies: OpFamily[];
  accessMethods: AccessMethod[];
  foreignTables: Map<string, ForeignTable>;
  fdws: Map<string, FDW>;
  foreignServers: Map<string, ForeignServer>;
  userMappings: UserMapping[];
  publications: Map<string, Publication>;
  subscriptions: Map<string, Subscription>;
  rules: Map<string, Rule>;
  eventTriggers: Map<string, EventTrigger>;
  textSearchConfigs: Map<string, TextSearchConfig>;
  textSearchDictionaries: Map<string, TextSearchDictionary>;
  textSearchParsers: Map<string, TextSearchParser>;
  textSearchTemplates: Map<string, TextSearchTemplate>;
  conversions: Map<string, Conversion>;
  defaultPrivileges: DefaultPrivilege[];
  fingerprints: Map<string, string>;
  introspectedAt: Date;
}

diff(desired, current)

Detect changes between two schema snapshots.

const changes = engine.diff(desiredSnapshot, currentSnapshot);
Parameter Type Description
desired SchemaSnapshot Target schema state
current SchemaSnapshot Current database state

Returns: SchemaDiff

interface SchemaDiff {
  changes: Change[];
  created: Change[];
  altered: Change[];
  dropped: Change[];
  renamed: Change[];
}

interface Change {
  changeType: 'CREATE' | 'ALTER' | 'DROP' | 'RENAME';
  objectType: ObjectType;
  objectKey: string;         // 'schema.object'
  properties?: PropertyDiff[];
  fromValue?: any;
  toValue?: any;
  risk: RiskLevel;
  sql?: string;
}

interface PropertyDiff {
  name: string;
  from: any;
  to: any;
}

generateDDL(diff)

Generate PostgreSQL DDL statements.

const ddl = engine.generateDDL(diff);
Parameter Type Description
diff SchemaDiff Schema diff from diff()

Returns: string[] - Array of DDL statements


plan(diff)

Create dependency-ordered migration plan.

const plan = engine.plan(diff);
Parameter Type Description
diff SchemaDiff Schema diff from diff()

Returns: MigrationPlan

interface MigrationPlan {
  steps: PlanStep[];
  phaseOrder: number[];
  blocked: boolean;
  blocker: Change | null;
  warnings: Warning[];
  estimatedDuration: number;  // ms
}

interface PlanStep {
  phase: number;
  change: Change;
  sql: string[];
  depends: string[];
  blockers: string[];
}

interface Warning {
  code: string;
  message: string;
  change: Change;
  severity: 'info' | 'warning' | 'error';
}

execute(pool, plan)

Execute migration plan.

const result = await engine.execute(pool, plan);
Parameter Type Description
pool pg.Pool PostgreSQL connection pool
plan MigrationPlan Plan from plan()

Returns: Promise<ExecutionResult>

interface ExecutionResult {
  migrationId: string;
  status: 'success' | 'partial' | 'failed';
  applied: string[];         // SQL statements applied
  failed?: string;           // SQL that failed
  error?: Error;
  duration: number;          // ms
  snapshotBefore: SchemaSnapshot;
  snapshotAfter?: SchemaSnapshot;
}

migrate(pool, desired)

One-shot migration: introspect → diff → plan → execute.

const result = await engine.migrate(pool, desiredSnapshot);
Parameter Type Description
pool pg.Pool PostgreSQL connection pool
desired SchemaSnapshot Target schema state

Returns: Promise<ExecutionResult>


rollback(pool, migrationId)

Revert a migration (best-effort).

const result = await engine.rollback(pool, 'migration-uuid');
Parameter Type Description
pool pg.Pool PostgreSQL connection pool
migrationId string UUID of migration to rollback

Returns: Promise<ExecutionResult>


Configuration

const engine = new PgMigrationEngine({
  riskThreshold: 'high',              // Block changes at this level or above
  allowForce: false,                  // Allow force flag for destructive changes
  storage: 'postgresql',              // 'postgresql' | 'memory' | 'file'
  storageConfig: {                    // Only for 'postgresql' storage
    tableName: 'migration_history'
  },
  lockTimeout: 60000,                 // Advisory lock timeout (ms)
  dryRun: false,                      // Preview changes without applying
});

Risk Levels

type RiskLevel = 'none' | 'low' | 'medium' | 'high' | 'critical';
Level Examples Default Action
none CREATE TABLE, ADD nullable column Allow
low ADD COLUMN with default, CREATE INDEX Allow
medium ALTER COLUMN type (widening) Allow
high DROP INDEX, ALTER type (narrowing) Block
critical DROP TABLE, DROP COLUMN Block

Events

engine.on('change:detected', (change) => { ... });
engine.on('ddl:generated', (sql) => { ... });
engine.on('step:started', (step) => { ... });
engine.on('step:completed', (step) => { ... });
engine.on('drift:detected', (drift) => { ... });
engine.on('error', (error) => { ... });

Errors

class IntrospectionError extends Error { ... }
class DiffError extends Error { ... }
class DDLGenerationError extends Error { ... }
class PlanningError extends Error { ... }
class ExecutionError extends Error { ... }
class DriftDetectedError extends Error { ... }
class MigrationBlockedError extends Error { ... }

See Also

Clone this wiki locally