Relational Schema Generator

0.6.3 · active · verified Wed Apr 22

Relational-schema is a utility package designed to introspect and generate a comprehensive, semantic schema representation of a relational database (currently supporting PostgreSQL and MySQL) into various developer-friendly formats. It outputs schema definitions as JavaScript, TypeScript, CommonJS, or JSON files. Currently at version 0.6.3, the package receives regular updates, primarily bug fixes and feature enhancements, though minor version increments (0.x.x) may introduce breaking changes without a major version bump. Unlike simplified ORM models, it provides a detailed schema including full table definitions, columns with types, default values, nullability, keys, constraints, unique key combinations, and intricate table relations with human-readable aliases, soft-delete identification, and enums. This tool aims to leverage the strictness of relational schemas for building more robust and automated tooling, such as the Gybson query client.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates programmatic database introspection and schema file generation using the library's core functions, including setting environment variables for credentials and handling output files. It also outlines the more common CLI usage.

import { generateSchema, introspectSchema } from 'relational-schema';
import fs from 'node:fs/promises';
import path from 'node:path';

async function runSchemaGeneration() {
  const config = {
    host: process.env.DB_HOST ?? '127.0.0.1',
    client: process.env.DB_CLIENT ?? 'postgres', // or 'mysql'
    port: parseInt(process.env.DB_PORT ?? '5432', 10), // 3306 for mysql
    user: process.env.DB_USER ?? 'postgres',
    password: process.env.DB_PASSWORD ?? 'secure_password',
    database: process.env.DB_NAME ?? 'mydb',
    outdir: './src/schemas',
    format: 'typescript'
  };

  try {
    console.log('Introspecting database schema...');
    const schema = await introspectSchema(config);
    console.log('Schema introspected successfully. Generating files...');

    // The generateSchema function returns an object of { filePath: content }
    const generatedFiles = await generateSchema(schema, config);

    await fs.mkdir(config.outdir, { recursive: true });

    for (const [fileName, content] of Object.entries(generatedFiles)) {
      const fullPath = path.join(config.outdir, fileName);
      await fs.writeFile(fullPath, content);
      console.log(`Generated: ${fullPath}`);
    }
    console.log('Schema generation complete!');
  } catch (error) {
    console.error('Failed to generate schema:', error);
    process.exit(1);
  }
}

// To run this example, ensure you have a database running and set environment variables.
// Example of typical CLI usage:
// 1. Create a `relation-config.json` in your project root:
//    {
//        "host": "127.0.0.1", "client": "postgres", "port": 5432,
//        "user": "postgres", "password": "secure_password",
//        "database": "mydb", "outdir": "src/schemas", "format": "typescript"
//    }
// 2. Run from your terminal:
//    npx relations introspect

runSchemaGeneration();

view raw JSON →