{"id":16521,"library":"relational-schema","title":"Relational Schema Generator","description":"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.","status":"active","version":"0.6.3","language":"javascript","source_language":"en","source_url":"https://github.com/MattGson/relational-schema","tags":["javascript","postgres","mysql","schema","typescript","sql","orm"],"install":[{"cmd":"npm install relational-schema","lang":"bash","label":"npm"},{"cmd":"yarn add relational-schema","lang":"bash","label":"yarn"},{"cmd":"pnpm add relational-schema","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"Primary function for programmatically fetching schema metadata from a connected database.","wrong":"const introspectSchema = require('relational-schema').introspectSchema;","symbol":"introspectSchema","correct":"import { introspectSchema } from 'relational-schema';"},{"note":"Used for programmatic generation of schema files (e.g., TypeScript, JSON) based on introspected data.","wrong":"const generateSchema = require('relational-schema').generateSchema;","symbol":"generateSchema","correct":"import { generateSchema } from 'relational-schema';"},{"note":"Import for the TypeScript type definition of the generated database schema structure, enabling type-safe interaction with the schema data.","wrong":"import { DatabaseSchema } from 'relational-schema';","symbol":"DatabaseSchema","correct":"import type { DatabaseSchema } from 'relational-schema';"}],"quickstart":{"code":"import { generateSchema, introspectSchema } from 'relational-schema';\nimport fs from 'node:fs/promises';\nimport path from 'node:path';\n\nasync function runSchemaGeneration() {\n  const config = {\n    host: process.env.DB_HOST ?? '127.0.0.1',\n    client: process.env.DB_CLIENT ?? 'postgres', // or 'mysql'\n    port: parseInt(process.env.DB_PORT ?? '5432', 10), // 3306 for mysql\n    user: process.env.DB_USER ?? 'postgres',\n    password: process.env.DB_PASSWORD ?? 'secure_password',\n    database: process.env.DB_NAME ?? 'mydb',\n    outdir: './src/schemas',\n    format: 'typescript'\n  };\n\n  try {\n    console.log('Introspecting database schema...');\n    const schema = await introspectSchema(config);\n    console.log('Schema introspected successfully. Generating files...');\n\n    // The generateSchema function returns an object of { filePath: content }\n    const generatedFiles = await generateSchema(schema, config);\n\n    await fs.mkdir(config.outdir, { recursive: true });\n\n    for (const [fileName, content] of Object.entries(generatedFiles)) {\n      const fullPath = path.join(config.outdir, fileName);\n      await fs.writeFile(fullPath, content);\n      console.log(`Generated: ${fullPath}`);\n    }\n    console.log('Schema generation complete!');\n  } catch (error) {\n    console.error('Failed to generate schema:', error);\n    process.exit(1);\n  }\n}\n\n// To run this example, ensure you have a database running and set environment variables.\n// Example of typical CLI usage:\n// 1. Create a `relation-config.json` in your project root:\n//    {\n//        \"host\": \"127.0.0.1\", \"client\": \"postgres\", \"port\": 5432,\n//        \"user\": \"postgres\", \"password\": \"secure_password\",\n//        \"database\": \"mydb\", \"outdir\": \"src/schemas\", \"format\": \"typescript\"\n//    }\n// 2. Run from your terminal:\n//    npx relations introspect\n\nrunSchemaGeneration();","lang":"typescript","description":"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."},"warnings":[{"fix":"Pin package versions in your `package.json` to prevent unintended updates, and carefully review the GitHub release notes or changelog before performing any minor version upgrades.","message":"As `relational-schema` is currently in `0.x.x` versions, minor version increments (e.g., `0.5.x` to `0.6.x`) may introduce breaking changes to the generated schema structure, programmatic API, or configuration options without adhering strictly to semantic versioning. Always review changelogs when upgrading.","severity":"breaking","affected_versions":">=0.0.0"},{"fix":"Grant `SELECT` permissions on relevant system schemas and tables to the configured database user. For PostgreSQL, this typically includes `pg_catalog` and `information_schema`.","message":"The database user configured in `relation-config.json` (or programmatic config) must possess sufficient permissions to query the database's information schema (e.g., `information_schema` and `pg_catalog` in PostgreSQL, `information_schema` in MySQL) for `relational-schema` to fully introspect the database. Insufficient permissions will result in an incomplete or failed schema generation.","severity":"gotcha","affected_versions":"*"},{"fix":"Verify that the database client is properly installed and configured on the system where `relational-schema` is executed, and ensure that all connection parameters (host, port, user, password, database) are correct and the database is accessible.","message":"For both programmatic usage and the CLI, `relational-schema` relies on underlying database drivers (e.g., `pg` for PostgreSQL, `mysql2` for MySQL) to connect. While these are usually internal dependencies, ensuring your environment has compatible native client libraries or that the Node.js drivers are correctly managed is crucial to prevent connection failures.","severity":"gotcha","affected_versions":"*"},{"fix":"If your database includes partitioned tables, carefully review the generated schema after updating to `0.6.3` or newer to confirm it aligns with your expected database structure. This update is generally a positive refinement.","message":"Version `0.6.3` introduced a bug fix to specifically exclude partition children from introspection results. This change might subtly alter the generated schema for partitioned tables compared to prior versions, aiming for greater accuracy.","severity":"gotcha","affected_versions":">=0.6.3"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Verify your database server's operational status and confirm the `host` and `port` values in your configuration accurately reflect your database connection.","cause":"The database server is not running, or the host/port configured in your `relation-config.json` or programmatic settings is incorrect or unreachable from where `relational-schema` is executed.","error":"Error: connect ECONNREFUSED <host>:<port>"},{"fix":"Install the package globally using `npm install -g relational-schema`, or execute the command directly via `npx relational-schema introspect` to use the local installation.","cause":"The `relational-schema` CLI binary (`relations`) is not installed globally or is not included in your system's PATH environment variable.","error":"relations: command not found"},{"fix":"Grant `SELECT` permissions on the relevant system schemas and tables (e.g., `pg_catalog`, `information_schema`) to the database user used by `relational-schema`.","cause":"The database user specified in your configuration lacks sufficient permissions to read the necessary system catalog tables required for schema introspection.","error":"ERROR: permission denied for relation pg_namespace (PostgreSQL example)"},{"fix":"Create a `relation-config.json` file in your project root or current directory, or use the `--config <path/to/config.json>` flag to specify its exact location.","cause":"The `relations introspect` command was run without a `relation-config.json` file in the current working directory, and no alternative configuration file path was provided.","error":"Missing config file: relation-config.json"}],"ecosystem":"npm"}