sql-ddl-to-json-schema
Version:
Parse and convert SQL DDL statements to a JSON Schema.
108 lines (107 loc) • 3.26 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Table = void 0;
const utils_1 = require("../../../../shared/utils");
const column_1 = require("./column");
/**
* Class to represent a table as parsed from compact format.
*/
class Table {
/**
* Table columns.
*/
columns = [];
/**
* Table name.
*/
name;
/**
* Table comment.
*/
comment;
/**
* Create Table instance from compact JSON format.
*
* @param json Table in compact JSON format.
*/
static fromCompactJson(json) {
const table = new Table();
table.name = json.name;
if ((0, utils_1.isDefined)(json.columns)) {
table.columns = json.columns.map((c) => column_1.Column.fromCompactJson(c));
}
if ((0, utils_1.isDefined)(json.primaryKey)) {
/**
* Set property in column(s) that is/are primary key(s).
*/
(json.primaryKey.columns ?? [])
.map((c) => c.column)
.map((name) => table.columns.find((c) => c.name === name))
.filter(utils_1.isDefined)
.forEach((column) => {
column.isPrimaryKey = true;
});
}
const options = json.options;
if (options) {
if ((0, utils_1.isDefined)(options.comment)) {
table.comment = options.comment;
}
}
return table;
}
/**
* JSON casting of this object calls this method.
* @param options Options available to format as JSON Schema.
*/
toJSON(options) {
const json = {
$schema: 'http://json-schema.org/draft-07/schema',
$comment: `JSON Schema for ${this.name} table`,
$id: this.name,
title: this.name,
description: '',
type: 'object',
required: [],
definitions: {},
properties: {},
};
if ((0, utils_1.isDefined)(this.comment)) {
json.description = this.comment;
}
else {
delete json.description;
}
this.columns.forEach((c) => {
const column = c.toJSON();
const name = c.name;
const definitions = {};
json.properties = {
...json.properties,
[name]: {
$ref: `#/definitions/${name}`,
},
};
Object.getOwnPropertyNames(column).forEach((key) => {
(0, utils_1.setProperty)(definitions, key, column[key]);
});
json.definitions = {
...json.definitions,
[name]: definitions,
};
if (c.isNullable === false) {
json.required.push(name);
}
});
/**
* Option to not use $ref, and have properties flattened out to 'properties' node.
* https://github.com/duartealexf/sql-ddl-to-json-schema/issues/36
*/
if (options.useRef === false) {
json.properties = json.definitions;
delete json.definitions;
}
return json;
}
}
exports.Table = Table;