PostgreSQL Schema Extractor
extract-pg-schema is a utility library designed to programmatically extract comprehensive metadata from a PostgreSQL database and return it as a structured JavaScript object. Currently stable at version 5.8.1, the package maintains an active release schedule, frequently delivering patch and minor updates to enhance features and ensure compatibility. It serves as a foundational component for other tools like Kanel, which leverages its output to generate TypeScript types, and Schemalint, used for database schema linting. A key differentiator is its ability to integrate seamlessly with standard `node-postgres` connection configurations and its provision of both a flexible programmatic API and a convenient command-line interface, making it adaptable for various use cases ranging from automated code generation to direct schema inspection.
Common errors
-
Error: connect ECONNREFUSED 127.0.0.1:5432
cause The PostgreSQL database server is not running or is not accessible at the specified host and port.fixVerify that your PostgreSQL server is running. Check your connection configuration (host, port, user, password) for accuracy. Ensure no firewall is blocking the connection to the database port. -
Error: Database 'nonexistent_db' does not exist
cause The database name provided in the connection configuration does not correspond to an existing database on the server.fixDouble-check the `database` property in your connection object or the `-d` option when using the CLI to ensure it matches an actual database name. -
TypeError: extractSchemas is not a function
cause This typically occurs when attempting to `require` or incorrectly `import` the function from an ESM-first package in a CommonJS context, or if using incorrect named/default import syntax.fixFor ESM projects (Node.js >=16, `"type": "module"` in `package.json`), use `import { extractSchemas } from 'extract-pg-schema';`. If strictly in CommonJS, you might need to ensure your environment supports dynamic `import()` or adjust your build system if direct `require` fails.
Warnings
- breaking Support for extracting window and aggregate functions was partially removed. If your application relied on detailed metadata for these function types, this change might affect your schema analysis.
- breaking The method for extracting triggers was changed in v5.7.2 to no longer rely on `information_schema`. While intended as a fix for certain edge cases, this change might alter the structure or completeness of trigger data for some database setups.
- gotcha Starting with version 5.7.4, `knex-pglite` was updated to declare `pglite` as a peer dependency. If you were implicitly relying on `extract-pg-schema` to provide `pglite` and are using features that leverage it (e.g., in testing environments), you might now need to explicitly install `pglite` in your project.
- gotcha The package maintains compatibility with Node.js >=16.0.0 and ships TypeScript types. While the README might show CommonJS `require()` examples, the primary and recommended way to import is using ESM `import` statements. Mixing ESM and CJS in some projects can lead to `TypeError: extractSchemas is not a function` or similar import errors.
Install
-
npm install extract-pg-schema -
yarn add extract-pg-schema -
pnpm add extract-pg-schema
Imports
- extractSchemas
const { extractSchemas } = require('extract-pg-schema');import { extractSchemas } from 'extract-pg-schema'; - ExtractSchemasOptions
import type { ExtractSchemasOptions } from 'extract-pg-schema'; - PgSchema
import type { PgSchema } from 'extract-pg-schema';
Quickstart
import { extractSchemas } from 'extract-pg-schema';
async function run() {
// Ensure your PostgreSQL server is running and accessible
// Environment variables (PGHOST, PGPORT, PGUSER, PGPASSWORD, PGDATABASE)
// are also supported by node-postgres for connection configuration.
const connection = {
host: process.env.PGHOST ?? 'localhost',
port: parseInt(process.env.PGPORT ?? '5432', 10),
database: process.env.PGDATABASE ?? 'postgres',
user: process.env.PGUSER ?? 'postgres',
password: process.env.PGPASSWORD ?? 'postgres',
};
try {
console.log('Connecting to PostgreSQL database...');
const result = await extractSchemas(connection, {
includeSchemas: ['public'], // Only extract schemas matching 'public'
excludeTables: ['^pg_'], // Exclude tables starting with 'pg_'
});
console.log('Successfully extracted schemas.');
// console.log(JSON.stringify(result, null, 2)); // Uncomment to see full schema object
// Example: Accessing a specific table from the 'public' schema
const publicSchema = result.find(s => s.name === 'public');
if (publicSchema) {
const usersTable = publicSchema.tables.find(t => t.name === 'users');
if (usersTable) {
console.log(`Found 'users' table in 'public' schema with ${usersTable.columns.length} columns.`);
} else {
console.log("No 'users' table found in 'public' schema.");
}
} else {
console.log("No 'public' schema found.");
}
} catch (error) {
console.error('Failed to extract schema:', error.message);
process.exit(1);
}
}
run();