PostgreSQL Schema Extractor

5.8.1 · active · verified Wed Apr 22

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

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to connect to a PostgreSQL database using environment variables or a direct connection config, extract specific schemas, and then log basic information about the extracted schema, such as table and column counts.

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();

view raw JSON →