All Projects → duartealexf → sql-ddl-to-json-schema

duartealexf / sql-ddl-to-json-schema

Licence: MIT license
SQL DDL to JSON Schema Converter

Programming Languages

typescript
32286 projects
Nearley
35 projects
javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to sql-ddl-to-json-schema

php-simple-request
php-simple-request is a request parser library designed to simplify requests validation and filtering using annotations, generating at the same time an object representation from the request data.
Stars: ✭ 15 (-89.13%)
Mutual labels:  json-schema
element-schema-form
A schema-based element-ui form component for Vue2.x.
Stars: ✭ 31 (-77.54%)
Mutual labels:  json-schema
phpunit-json-assertions
JSON assertions for PHPUnit (including JSON Schema)
Stars: ✭ 30 (-78.26%)
Mutual labels:  json-schema
jgeXml
The Just-Good-Enough XML Toolkit
Stars: ✭ 20 (-85.51%)
Mutual labels:  json-schema
flowjv
Flow based approach to JSON validation.
Stars: ✭ 20 (-85.51%)
Mutual labels:  json-schema
schema
SpaceAPI JSON schema files.
Stars: ✭ 20 (-85.51%)
Mutual labels:  json-schema
scalable-form-platform
A solution for building dynamic web forms with visual editor
Stars: ✭ 109 (-21.01%)
Mutual labels:  json-schema
universal-json-schema
📜 Universal JSON Schema Form - Currently Support for React - Material UI components for building Web forms from JSON Schema.
Stars: ✭ 102 (-26.09%)
Mutual labels:  json-schema
Minecraft-bedrock-json-schemas
The JSON validation schema files for Minecraft bedrock
Stars: ✭ 17 (-87.68%)
Mutual labels:  json-schema
jsons2xsd
Highly configurable converter from JSON-schema to XML-schema (XSD).
Stars: ✭ 65 (-52.9%)
Mutual labels:  json-schema
JsonSettings
This library simplifies creating configuration for your C# app/service by utilizing the serialization capabilities of Json.NET to serialize nested (custom) objects, dictionaries and lists as simply as by creating a POCO and inheriting JsonSettings class.
Stars: ✭ 59 (-57.25%)
Mutual labels:  json-schema
hull
The incredible HULL - Helm Uniform Layer Library - is a Helm library chart to improve Helm chart based workflows
Stars: ✭ 66 (-52.17%)
Mutual labels:  json-schema
garden-schema
A simple data validation and cleaning library based on OpenAPI 3.0 Schema.
Stars: ✭ 21 (-84.78%)
Mutual labels:  json-schema
JustJson
JSON helper library for Android
Stars: ✭ 15 (-89.13%)
Mutual labels:  json-schema
json-schema-migrate
Migrate JSON-Schema draft-04 to draft-07, draft-2019-09 or draft-2020-12
Stars: ✭ 18 (-86.96%)
Mutual labels:  json-schema
flow2schema
Generate json-schemas for flowtype definitions
Stars: ✭ 20 (-85.51%)
Mutual labels:  json-schema
sf-java-ui
Json Schema Form java based library allow developers to define schema and form using field annotations
Stars: ✭ 23 (-83.33%)
Mutual labels:  json-schema
ontology
Global Insurance Ontology
Stars: ✭ 71 (-48.55%)
Mutual labels:  json-schema
sqlfun
Modern SQL parser using Bison (Yacc) and Flex
Stars: ✭ 63 (-54.35%)
Mutual labels:  sql-parser
jsonschema-generator
Java JSON Schema Generator – creating JSON Schema (Draft 6, Draft 7, Draft 2019-09, or Draft 2020-12) from Java classes
Stars: ✭ 213 (+54.35%)
Mutual labels:  json-schema

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": 1.5474250491067253e+26
      },
      "nickname": {
        "type": "string",
        "maxLength": 255
      },
      "deleted_at": {
        "type": "string"
      },
      "created_at": {
        "type": "string"
      },
      "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",
          "width": 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"
          }
        ],
        "name": "unq_nick"
      }
    ],
    "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 = {};

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

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

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

The tests call SQL statements on the parser and test the JSON result (whatever the format) against a JSON file in a folder called expect, for that test case. The command below updates all expect files to whatever is being parsed in the test cases. This is useful when there is a change in the parser that affects many files and changes JSON result in them. Run the script to update the expected parse result in the file:

npm run test:update

Visual Studio Code

Debug launch config is versioned in this repository.

Links

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].