pg-god: PostgreSQL Database Management

1.0.12 · active · verified Wed Apr 22

pg-god is a focused JavaScript/TypeScript library (current stable version 1.0.12) designed to simplify the creation and deletion of PostgreSQL databases, both programmatically and via a command-line interface. Its primary function is to manage database lifecycles, often in development or testing environments where databases need to be frequently spun up and torn down. Key differentiators include its minimalist API for direct database creation/dropping, support for connection URLs (added in v1.0.9), and a default behavior since v1.0.6 to automatically terminate active connections before dropping a database, preventing common errors. It also provides explicit integration guidance for TypeORM users. The project appears to have a moderate release cadence, with recent updates refining CLI behavior and adding new features.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates programmatic creation and immediate dropping of a PostgreSQL database using environment variables for credentials and handling potential errors.

import { createDatabase, dropDatabase, DbCredential } from 'pg-god';

async function main() {
  const dbConfig = { databaseName: 'my_app_test_db' };
  const credentials: Partial<DbCredential> = {
    user: process.env.PG_USER ?? 'postgres',
    password: process.env.PG_PASSWORD ?? '',
    host: process.env.PG_HOST ?? 'localhost',
    port: parseInt(process.env.PG_PORT ?? '5432', 10),
    database: process.env.PG_INITIAL_DB ?? 'postgres', // Initial database to connect to
  };

  try {
    console.log(`Attempting to create database: ${dbConfig.databaseName}`);
    await createDatabase(dbConfig, credentials);
    console.log(`Database '${dbConfig.databaseName}' created successfully.`);

    // --- Your application logic or tests would go here ---

    console.log(`Attempting to drop database: ${dbConfig.databaseName}`);
    // dropConnections: true is default since v1.0.6, but explicit for clarity
    await dropDatabase({ ...dbConfig, dropConnections: true }, credentials);
    console.log(`Database '${dbConfig.databaseName}' dropped successfully.`);
  } catch (error) {
    console.error('An error occurred during database operation:', error);
    // Attempt to clean up even if an error occurred after creation
    try {
        await dropDatabase({ ...dbConfig, dropConnections: true, errorIfNonExist: false }, credentials);
        console.log(`Attempted cleanup for database '${dbConfig.databaseName}'.`);
    } catch (cleanupError) {
        console.warn(`Failed to clean up database '${dbConfig.databaseName}':`, cleanupError);
    }
    process.exit(1);
  }
}

main();

view raw JSON →