Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

sql-ddl-to-json-schema

duartealexf7kMIT6.0.0TypeScript support: included

Parse and convert SQL DDL statements to a JSON Schema.

parse, parser, sql, ddl, format, formatter, json, schema, jsonschema, convert, converter

readme

SQL DDL to JSON Schema converter

Tests npm node license

Transforms SQL DDL statements into JSON format (JSON Schema and a compact format).

Overview

Taking the following SQL:

CREATE TABLE users (
  id INT(11) NOT NULL AUTO_INCREMENT,
  nickname VARCHAR(255) NOT NULL,
  deleted_at TIMESTAMP NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
  updated_at TIMESTAMP,
  PRIMARY KEY (id)
) ENGINE MyISAM COMMENT 'All system users';

ALTER TABLE users ADD UNIQUE KEY unq_nick (nickname);

It parses and delivers an array of JSON Schema documents (one for each parsed table):

[
  {
    "$schema": "http://json-schema.org/draft-07/schema",
    "$comment": "JSON Schema for users table",
    "$id": "users",
    "title": "users",
    "description": "All system users",
    "type": "object",
    "required": [
      "id",
      "nickname",
      "created_at"
    ],
    "definitions": {
      "id": {
        "$comment": "primary key",
        "type": "integer",
        "minimum": 1,
        "maximum": 2147483647
      },
      "nickname": {
        "type": "string",
        "maxLength": 255
      },
      "deleted_at": {
        "type": "string"
      },
      "created_at": {
        "type": "string",
        "default": "CURRENT_TIMESTAMP"
      },
      "updated_at": {
        "type": "string"
      }
    },
    "properties": {
      "id": {
        "$ref": "#/definitions/id"
      },
      "nickname": {
        "$ref": "#/definitions/nickname"
      },
      "deleted_at": {
        "$ref": "#/definitions/deleted_at"
      },
      "created_at": {
        "$ref": "#/definitions/created_at"
      },
      "updated_at": {
        "$ref": "#/definitions/updated_at"
      }
    }
  }
]

And an array of tables in a compact JSON format:

[
  {
    "name": "users",
    "columns": [
      {
        "name": "id",
        "type": {
          "datatype": "int",
          "displayWidth": 11
        },
        "options": {
          "nullable": false,
          "autoincrement": true
        }
      },
      {
        "name": "nickname",
        "type": {
          "datatype": "varchar",
          "length": 255
        },
        "options": {
          "nullable": false
        }
      },
      {
        "name": "deleted_at",
        "type": {
          "datatype": "timestamp",
          "fractional": 0
        },
        "options": {
          "nullable": true
        }
      },
      {
        "name": "created_at",
        "type": {
          "datatype": "timestamp",
          "fractional": 0
        },
        "options": {
          "nullable": false,
          "default": "CURRENT_TIMESTAMP"
        }
      },
      {
        "name": "updated_at",
        "type": {
          "datatype": "timestamp",
          "fractional": 0
        },
        "options": {
          "nullable": true
        }
      }
    ],
    "primaryKey": {
      "columns": [
        {
          "column": "id"
        }
      ]
    },
    "uniqueKeys": [
      {
        "columns": [
          {
            "column": "nickname",
            "length": 255
          }
        ]
      }
    ],
    "options": {
      "comment": "All system users",
      "engine": "MyISAM"
    }
  }
]

Currently only DDL statements of MySQL and MariaDB dialects are supported. - Check out the roadmap

Installation

yarn add sql-ddl-to-json-schema
npm i sql-ddl-to-json-schema

Usage

Shorthand

const { Parser } = require('sql-ddl-to-json-schema');
// or:
import { Parser } from 'sql-ddl-to-json-schema';

const parser = new Parser('mysql');

const sql = `
CREATE TABLE users (
  id INT(11) NOT NULL AUTO_INCREMENT,
  nickname VARCHAR(255) NOT NULL,
  deleted_at TIMESTAMP NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
  updated_at TIMESTAMP,
  PRIMARY KEY (id)
) ENGINE MyISAM COMMENT 'All system users';

ALTER TABLE users ADD UNIQUE KEY unq_nick (nickname);
`;

/**
 * Read on for available options.
 */
const options = {};

/**
 * Explore the compact JSON format...
 */
const compactJsonTablesArray = parser.feed(sql).toCompactJson(parser.results);

/**
 * Or get the JSON Schema if you need to modify it...
 */
const jsonSchemaDocuments = parser.feed(sql).toJsonSchemaArray(options, compactJsonTablesArray);

Step by step

/**
 * Read on for available options.
 */
const options = { useRef: true };

/**
 * Feed the parser with the SQL DDL statements...
 */
parser.feed(sql);

/**
 * You can get the parsed results in JSON format...
 */
const parsedJsonFormat = parser.results;

/**
 * And pass it to be formatted in a compact JSON format...
 */
const compactJsonTablesArray = parser.toCompactJson(parsedJsonFormat);

/**
 * Finally pass it to format to an array of JSON Schema items. One for each table...
 */
const jsonSchemaDocuments = parser.toJsonSchemaArray(options, compactJsonTablesArray);

Options for JSON Schema output

There are a few options when it comes to formatting the JSON Schema output:

useRef

Whether to add all properties to definitions and in properties only use $ref.

Default value: true.

Version compatibility table

This lib version range NodeJS version range Angular support Other browser-based JS support
<= 3.x >= 6.x No Yes
>= 4 >= 8.6 Yes Yes

What it is, what it is not

It is a SQL DDL parser for Javascript, based on nearley. It will parse DDL statements only, converting it to JSON. No DML is supported.

It is not a SQL DBMS, nor a SQL Server, nor SQL client.

About

No SQL server, client or DBMS is required.

To see which DDL statements / SQL dialects are supported, check out the roadmap.

This project is a grammar and stream-friendly SQL parser based on nearley.

Contributing

You are welcome to contribute!

Preferably use npm, as all scripts in package.json are run through npm.

  • Clone this repo
  • Install dependencies: npm i

Commiting

Prefer using the latest version of NodeJS.

To commit, use commitizen: git cz (you will need to have installed devDependencies: npm i).

Understanding the internals

Folder structure:

|- lib/ Compiled library folder, product of this project.
|
|- src/
| |- typings/ Types used throughout project.
| |- shared/ Shared files used by dialects, parsers and formatters.
| |- mysql/
| |- formatter/ Formats the parsed JSON (output of parser) to other format.
| |- compact/ Formatter for compact JSON format.
| |- json-schema/ Formatter for JSON Schema format.
| |- language/
| |- dictionary/ TS files with array of keywords and symbols used in lexer.ne.
| |- rules/ Nearley files with grammar rules.
| |- lexer.ne Entrypoint and first lines of the grammar.
|
|- tasks/
| |- mysql/
| |- assembly.ts Script that concatenates all .ne files to grammar.ne to lib folder.
| |- formatters.ts Script that sends a copy of formatters to lib folder.
|
|- test/ Tests.
  • There are naming rules for tokens in ne files, as stated in lexer.ne. They are prepended with:

K_ -> Keywords
P_ -> Phrase (aka statements)
O_ -> Options (one of several keywords or phrases)
S_ -> Symbol (not a keyword, but chars and other matches by RegExp's)
  1. The dictionary/keywords.ts file contains keywords, but they are prepended with K_ when used in .ne files. Take a look to make sure you understand how it is exported.

  2. The compiled grammar.ne file comprises an assembly (concatenation) of lexer.ne and files in language folder. So don't worry about importing .ne files in other .ne files. This prevents circular dependency and grammar rules in lexer.ne are scoped to all files (thus not having to repeat them in every file).

Scripts at hand

Valid to all SQL dialects:

  • Assemble grammar.ne and compile to grammar.ts: npm run build
  • Same as above, but watch for changes: npm run build:watch
  • Run tests: npm run test
  • Test and watch for changes: npm run test:watch

Visual Studio Code

Debug launch config is versioned in this repository.

changelog

Changelog

All notable changes to this project will be documented in this file. See standard-version for commit guidelines.

6.0.0 (2025-08-01)

5.0.0 (2025-01-13)

Breaking changes

  • Minimum node version is now 14.
  • Compact JSON format: width has been renamed to displayWidth, values are now different.
  • Compact JSON format: int datatypes ('tinyint', 'smallint', 'mediumint', 'int', 'bigint') names are preserved.
  • JSON Schema format: minimum and maximum values of some integer types have been changed.

Features

  • package.json: version 5.0.0 (483b6a9)
  • update int datatypes with compact json and jsonschema (f26b9f0)

Bug Fixes

  • mysql formatter jsonschema definitions should be optional (cf1d26e)
  • no change for the bigint type as integer in jsonschema (ce57308)
  • number types with wrong max and min, and add handling bigint in javascript (2a03bec)
  • remove extra feature jest configs and tests (6483d09)
  • rm tests ssn1 -> ssn9 int datatypes in sql (7bf3485)
  • src/mysql/formatter/json-schema/models/datatype.ts: fix datatype int signed or unsigned with max and min number value (76ccb20)
  • src/mysql/formatter/json-schema/models/datatype.ts: verbose Datatype isIntegerDataType method (4f342e5)
  • src/typings/compact.ts: verbose DatatypeInterface width (7bedfcc)
  • test - reduce the changes in snapshots (f094b8b)
  • tests/mysql/parser/create-table.spec.ts: reduce changes in snapshots (5a17007)

4.1.1 (2024-11-19)

Bug Fixes

  • fix alter last column (023eb4c)
  • fix alter last column (Merge pull request #98 from duartealexf/staging) (7f24844)

4.1.0 (2023-07-07)

Features

  • add support for nvarchar mysql datatype (7697b5c)
  • add support for uuid and uniqueidentifier types (d8c4cc5)

4.0.10 (2023-05-30)

4.0.9 (2023-02-13)

4.0.8 (2022-10-29)

4.0.7 (2022-09-16)

Bug Fixes

  • add binary collation support (a89e50f)

4.0.6 (2021-11-13)

4.0.5 (2021-11-13)

4.0.4 (2020-09-02)

4.0.3 (2020-07-19)

  • Add Node 14 to engines and CI tests

4.0.2 (2020-07-19)

  • Vulnerability fixes

4.0.1 (2020-03-23)

Bug Fixes

  • Fix package release build.

4.0.0 (2020-03-22)

⚠ BREAKING CHANGES

  • Removed toJSONSchemaFiles method from parser, as it caused build issues in Angular.
  • Changed export to named export (non-default). Now to import it, use braces, as in import { Parser } from 'sql-ddl-to-json-schema'.
  • The parsed format does not contain null values anymore. Instead, the values that used to be null are not mentioned at all in parsed JSON format.

Bug Fixes

  • Fix Angular compatibility. (29c640f), closes [#47]

Features

  • Add typing definitions.

3.1.3 (2020-03-11)

Bug Fixes

3.1.2 (2019-05-05)

Bug Fixes

  • Fix unsigned in JSON Schema output. (10a430f)

3.1.1 (2019-05-05)

Bug Fixes

  • Fix onUpdate column option for compact JSON. (36be786), closes #45

3.1.0 (2019-04-07)

Features

  • Add support for USE statement. (cefd1d7), closes #42

3.0.1 (2019-03-16)

Bug Fixes

  • Ignore formatting queries that do not affect tables. (3f88701), closes #41

3.0.0 (2019-01-13)

Bug Fixes

  • Timestamp initialization with triggers now working (32bbf7a)

Features

  • Add option to not use $ref in JSON Schema output. (713f1a1), closes #36
  • Allow initialization of timestamp (5f37b57) (Thanks @umegaya for the PR!)

BREAKING CHANGES

  • The toJsonSchemaArray method used to have only one argument: the tables array in compact JSON format. Now this array is the second argument to be passed to this method. The first argument refers to JSON Schema output options. Refer to the README for the list of options.

  • For those who use the parsed format directly: foreign key reference had to be moved out of the O_COLUMN_DEFINITION rule, moving it out of column options. This had to be done because of grammar ambiguity when parsing "ON DELETE" or "ON UPDATE" clauses, as it conflicted with the foreign key triggers. It is still compliant with MySQL and MariaDB syntaxes. It will not affect the compact JSON format nor the JSON Schema format.

2.2.0 (2018-07-22)

Bug Fixes

  • Add missing CHARSET alias. (367a14f), closes #28 #29
  • Add NULL option as default column value. (22d65a9), closes #26
  • Disabled foreign key checks. (78cddaf), closes #27
  • Fix behavior of preparsing with escaping chars. (eb9aad8), closes #21
  • Fix line count of parsing errors. (#30) (039ca75), closes #20
  • Set INDEX_COLUMN length as optional, as per MariaDB and MySQL docs. (a94fe33), closes #24

Features

  • Add support for basic function statements as default column values. (218fd6c), closes #25
  • Add support for SET statements. (bdfc327), closes #23
  • Add support for SQL comments. (#33) (dfffb37), closes #22

2.1.0 (2018-07-08)

Bug Fixes

  • Fix behavior when sending null arguments to parser. (46f6e46)

Features

  • Add validation to JSON Schema $id attribute when outputing to files. (32dd787)
  • JSON Schema output (7655c2b)

2.0.6 (2018-07-01)

Bug Fixes

  • Add default values of digits and decimals for fixed point datatype. (c7bffd7)

2.0.5 (2018-05-14)

Bug Fixes

  • Add check to not add auto increment without being a primary key. (fed92cd)
  • Add rename of fk references on table rename. (060a0e1)

2.0.4 (2018-05-13)

Bug Fixes

  • Update dependencies for Node v10. (#17) (898917b)

2.0.3 (2018-05-13)

Bug Fixes

  • Set max version of node to 9. (7e7d25d)

2.0.2 (2018-05-13)

Bug Fixes

  • Fix build for node 9 and code linting. (b4c1cc5)

2.0.1 (2018-05-13)

Bug Fixes

  • Add rename of column references when renaming column. (f9db921), closes #9
  • Skip copying of foreign keys in MySQL CREATE TABLE LIKE statement. (1e0d2db)

2.0.0 (2018-03-31)

Bug Fixes

  • Add checks to not have two columns with autoincrement. (ddcbb6c)
  • Add foreign key check when dropping a column. (ffa9936), closes #12
  • Add foreign key check when dropping tables. (ac5d2bc)
  • Bugfix on RENAME TABLE rule compact formatter. (b614b82)
  • Changed to ALTER TABLE ADD COLUMN having REFERENCES does not add FK. (36a02d0), closes #16
  • Fixed so it does not drop the last column of a table. (828ce79)
  • Removed 'symbol' property from indexes and keys. (c1b1f60), closes #14 #15

BREAKING CHANGES

  • Ambiguous and confusing 'symbol' property from indexes and keys was removed from compact JSON format. Through tests it is noticed that MySQL and MariaDB don't seem to use them.

1.2.0 (2018-03-23)

Bug Fixes

  • Bug fix in Index.clone method. (8a11ed6)

Features

  • Add clone method in models for CREATE TABLE LIKE, other improvements. (c6408ea), closes #8 #10 #11

1.1.0 (2018-03-20)

Features

  • parser: Add Parser.toCompactJson with no arguments, taking parsed SQL. (b4f713c)

1.0.2 (2018-03-20)

Bug Fixes

  • Fix build by adding moo as dependency. (717e2be)

1.0.1 (2018-03-20)

Bug Fixes

  • Changed .npmignore and .gitignore. (e52e238)

1.0.0 (2018-03-19)

Bug Fixes

  • rule: Fix last implementation of keyword-as-identifier. (c9a6ab6)
  • Add commitizen path. (e7af802)
  • rule: Fix keyword-as-identifier rule. (94e97ad)
  • Added SCHEMA as synonym for DATABASE. (a523cea)
  • Correct CREATE INDEX test name. (cf1e5a4)
  • Fix ambiguous interpretation of a FULLTEXT/SPATIAL INDEX/KEY. (7f7d828)
  • Fix apparent infinite loop on parsing rules. (de6c1cd)
  • Fix missing scripts and missing utils.js file. (d4f53fd)
  • Fix several bugs, order of keywords and tests. (22b50ed)
  • datatype: Add width of INT datatype. (70cbab2)
  • Fix support for multiple statements. (235f55b)
  • Fix syntax of datatypes and wip in CREATE TABLE statements. Add keywords. (da83fff)
  • Fixed import in example file. (aa5b715)
  • datatype: Correct returning values of datatypes. (d1017c6)
  • datatype: Fix bug in fractional field in DATETIME. (93817e9)
  • docs: Fix typo in README. (0b6f963)
  • keyword: Fix word boundary issues with keywords. Fix tests. (1d71ff0)
  • scripts: Fix typo in example script. (42d98a8)

Code Refactoring

  • Add assembly of .ne files into a single one. (463e9c4)

Features

  • Add ALTER DATABASE statement. (9e4f660)
  • Add ALTER TABLE add column, fulltext, spatial, index, primary and unique. (5081490)
  • Add ALTER TABLE foreign key options. (5c73430)
  • Add CREATE DATABASE statement parser. (ed85709)
  • Add CREATE INDEX. (a21b50b)
  • Add CREATE TABLE LIKE statement. (cdeccfd)
  • Add CREATE TABLE options, still not parsing though. (3dd4e97)
  • Add CREATE TABLE statement table options. (6f139cd)
  • Add DROP DATABASE statement. (e2f2e28)
  • Add DROP INDEX statement. (2bf5898)
  • Add DROP TABLE statement. (ccab54c)
  • Add FOREIGN KEY support. (6c37aa2)
  • Add FULLTEXT and SPATIAL index support. (9663354)
  • Add new ALTER TABLE statements. (80e2340)
  • Add new features in CREATE TABLE statement. (58f1c16)
  • Add PRIMARY KEY, INDEX and KEY column definitions. (54ca115)
  • Add remaining ALTER TABLE statements. (f685d72)
  • rule: Add more options to CREATE TABLE parse. (c8f94bc)
  • Add RENAME TABLE statement. (07878fb)
  • datatype: Add support for datatype. (76cd373)
  • Add UNIQUE key / index table definition. (d2366a7)
  • keyword: Add all keywords and reserved words from MySQL docs. (83b38f1)
  • keyword: Add CURRENT_TIMESTAMP option as a default value. (5c080ba)
  • keywords: Add function names to keywords. (67b41a3)
  • moo: Add moo and wip in code refactoring. (018f97c)
  • Add working complex example of CREATE TABLE. (ce4538e)
  • Added MariaDB compatibility to MySQL parser. (6c4ae0a)
  • symbols: Add new symbols. (f46ffdb)

Performance Improvements

  • Added preparser to separate statements, improving performance. (3895c86)
  • Removed unused keywords and symbols to improve performance. (8865f45)

BREAKING CHANGES

  • Create and alter table statements with key definitions had format changed, as Index and Key were treated differently. Since they are synonyms, some rules were grouped together and some were split in two.
  • rule: All %S_IDENTIFIER were changed to S_IDENTIFIER (no percent sign).
  • Changed Utils to class with static methods. Add utils to .ne files to make methods available.
  • Assembly of .ne files by concatenating into one, to prevent circular dependency. Improved directory structure and README documentation on Contributing section.
  • datatype: Support for datatypes changed the structure of the resulting struct, having default 'type' and 'def' fields. The former defines the name of what was parsed (the T_xxx, P_xxx, etc), while the latter has custom configurations according to the context. Tests are changed to support this new structure.