npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@khanakia/sql-schema-core

v0.1.0

Published

Framework-agnostic SQL DDL parser, ER layout and URL share codec for sql-schema-visualizer.

Downloads

41

Readme

@khanakia/sql-schema-core

Framework-agnostic SQL database schema parser, ER-diagram layout engine, and URL share codec. Zero React. Zero backend. Pure TypeScript that runs in Node, browsers, edge runtimes and web workers — the engine behind SQL Schema Visualizer.

types deps ESM

Parse PostgreSQL / MySQL / SQLite / ANSI CREATE TABLE DDL into a typed schema model, lay it out as a graph, and compress a whole schema into a shareable URL token — all client-side.


Why

Most SQL parsers are single-dialect, strict, and throw on the first vendor clause they don't recognise (ENGINE=InnoDB, AUTOINCREMENT, backticks). @khanakia/sql-schema-core is deliberately tolerant: it skips what it can't understand and still produces a useful diagram, surfacing problems as warnings[] instead of exceptions. Perfect for visualizers, docs generators, migration tools, lint rules, and LLM pipelines.

Install

npm i @khanakia/sql-schema-core
# or: pnpm add @khanakia/sql-schema-core

ESM-only, ships its own .d.ts. Only runtime dependency: @dagrejs/dagre.

Quick start

import { parseSchema, layoutGraph, encodeSql, decodeSql } from '@khanakia/sql-schema-core'

const sql = `
  CREATE TABLE customers ( id SERIAL PRIMARY KEY, email VARCHAR(255) NOT NULL UNIQUE );
  CREATE TABLE orders (
    id SERIAL PRIMARY KEY,
    customer_id INTEGER NOT NULL REFERENCES customers(id)
  );
`

const schema = parseSchema(sql)
schema.tables           // [{ name:'customers', columns:[...] }, { name:'orders', ... }]
schema.foreignKeys      // [{ fromTable:'orders', fromColumn:'customer_id', toTable:'customers', toColumn:'id' }]
schema.warnings         // string[] — never throws

// Lay it out (framework-agnostic: ids in, positions out)
const positions = layoutGraph(
  schema.tables.map(t => ({ id: t.name, columns: t.columns.length })),
  schema.foreignKeys.map(fk => ({ source: fk.fromTable, target: fk.toTable })),
  { direction: 'LR' },
)
positions.get('orders') // { x, y }

// Shareable, compressed URL token (deflate-raw + base64url, ~2.9x on SQL)
const token = await encodeSql(sql)        // URL-fragment safe
const back  = await decodeSql(token)      // original SQL (or null)

How it works

flowchart LR
  A["SQL DDL text"] --> B["stripComments<br/>quote-aware"]
  B --> C["splitStatements<br/>paren/quote depth"]
  C --> D{"statement?"}
  D -->|CREATE TABLE| E["columns + PK/FK/UNIQUE/DEFAULT"]
  D -->|ALTER ADD FK| F["foreign keys"]
  E --> G["associateComments<br/>re-attach comments"]
  F --> G
  G --> H["Schema: tables · foreignKeys · warnings"]
  H --> I["layoutGraph · dagre"]
  I --> J["Map id → x,y"]
  A -. encodeSql .-> K["deflate-raw + base64url token"]
  K -. decodeSql .-> A

API

parseSchema(sql: string): Schema

Tolerant multi-dialect parser. Handles PostgreSQL, MySQL, SQLite and generic ANSI: backticks, "quotes", [brackets], schema-qualified names, AUTO_INCREMENT/AUTOINCREMENT, UNSIGNED, composite keys, inline + table-level FOREIGN KEY, ALTER TABLE … ADD FOREIGN KEY, and -- / # / /* */ comments. Never throws.

interface Schema { tables: Table[]; foreignKeys: ForeignKey[]; warnings: string[] }
interface Table  { name: string; columns: Column[]; comment?: string }
interface Column {
  name: string; type: string; nullable: boolean
  pk: boolean; unique: boolean
  fk?: { table: string; column: string }
  default?: string; comment?: string
}
interface ForeignKey { fromTable: string; fromColumn: string; toTable: string; toColumn: string }

layoutGraph(nodes, edges, options?): Map<string, Point>

Directed-graph layout via dagre. Pure: takes { id, columns }[] + { source, target }[], returns top-left { x, y } per id. Cycles and self-references are handled (dagre breaks them for ranking, all edges preserved).

layoutGraph(nodes, edges, {
  direction?: 'LR' | 'TB',                       // default 'LR'
  collapsed?: Record<string, true>,              // ids rendered header-only
  commentsInline?: boolean,                      // taller height estimate
  sizes?: Map<string, { width; height }>,        // real measured sizes win
})

encodeSql(sql) / decodeSql(token)

Promise-based, native CompressionStream('deflate-raw') + base64url — zero deps, no WASM, ~2.9× on SQL. Token is URL-fragment safe. decodeSql returns null for blank/garbage input.

samples: Sample[]

Ready-made commented example schemas (e-commerce / blog / SaaS) for demos and tests.

Supported SQL

| Dialect | Notes | |---|---| | PostgreSQL | SERIAL, TIMESTAMPTZ, schema prefixes, array types | | MySQL | backticks, AUTO_INCREMENT, ENGINE=, UNSIGNED | | SQLite | AUTOINCREMENT, minimal types | | ANSI / generic | best-effort; unknown clauses skipped, not fatal |

Limitations

Not a full SQL grammar. Generated columns, partition clauses, deeply nested parens and CTE-in-DDL parse loosely. Comment continuation lines can anchor one row off. These are accepted trade-offs for a tolerant visual tool — see CONTEXT.md.

License

MIT © khanakia · Part of sql-schema-visualizer.