pg-god: PostgreSQL Database Management
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
-
Password authentication failed for user "your_user"
cause The PostgreSQL server rejected the connection attempt due to incorrect credentials (username or password) or an invalid entry in `pg_hba.conf`.fixEnsure the `user` and `password` in your `DbCredential` object (or CLI flags/environment variables) match the PostgreSQL server configuration. Verify `pg_hba.conf` allows connections from your host with the specified authentication method. -
database "your-db-name" does not exist
cause You are attempting to drop a database that does not exist, and `errorIfNonExist` is set to `true` (or implied by CLI usage).fixIf it's acceptable for the database not to exist, set `errorIfNonExist: false` in the `dropDatabase` call. Otherwise, ensure the database exists before attempting to drop it. -
cannot drop a database that is currently in use
cause Despite the default behavior since v1.0.6, this error can still occur if `dropConnections: false` is explicitly set, and there are active connections to the database you are trying to drop.fixEnsure `dropConnections: true` (the default since v1.0.6) is used when calling `dropDatabase`. If this is not an option, you must manually terminate all connections to the database before dropping it.
Warnings
- breaking The default behavior for `dropDatabase` (both API and CLI `db-drop` command) changed in v1.0.6. It now automatically kills all active connections to the target database before dropping it. Previously, this required manual intervention or would fail if connections existed.
- gotcha By default, `pg-god` uses 'postgres' for the user and 'localhost:5432' for the host/port, with an empty password. This often works for local development setups, but will likely cause 'Password authentication failed' errors in production or secured environments if not explicitly configured.
- gotcha When using `createDatabase` or `dropDatabase`, the `errorIfExist` (for create) and `errorIfNonExist` (for drop) options default to `false` for the programmatic API, meaning it will silently succeed even if the database state doesn't change. However, if set to `true`, attempting to create an existing DB or drop a non-existent DB will throw an error.
Install
-
npm install pg-god -
yarn add pg-god -
pnpm add pg-god
Imports
- createDatabase
const { createDatabase } = require('pg-god')import { createDatabase } from 'pg-god' - dropDatabase
const dropDatabase = require('pg-god').dropDatabaseimport { dropDatabase } from 'pg-god' - DbCredential
import { DbCredential } from 'pg-god'import type { DbCredential } from 'pg-god'
Quickstart
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();