UNPKG

sql-ddl-to-json-schema

Version:

Parse and convert SQL DDL statements to a JSON Schema.

75 lines (74 loc) 2.32 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Column = void 0; const utils_1 = require("../../../../shared/utils"); const datatype_1 = require("./datatype"); /** * Table column. */ class Column { name; datatype; isNullable; isPrimaryKey; comment; default; /** * Create Column instance from compact JSON format. * * @param json Column in compact JSON format. */ static fromCompactJson(json) { const column = new Column(); column.datatype = datatype_1.Datatype.fromCompactJson(json.type); column.name = json.name; const options = json.options; if (options) { if (options.unsigned) { column.datatype.isUnsigned = options.unsigned; } if (options.default === null || ((0, utils_1.isString)(options.default) && options.default.length)) { column.default = options.default; } if ((0, utils_1.isString)(options.comment) && options.comment.length) { column.comment = options.comment; } column.isNullable = options.nullable; } return column; } /** * JSON casting of this object calls this method. */ toJSON() { const json = {}; const type = this.datatype.toJSON(); /** * Special treatment for primary keys. */ if (this.isPrimaryKey === true) { json.$comment = 'primary key'; if (type.type === 'integer' || type.type === 'number') { type.minimum = 1; } } if ((0, utils_1.isDefined)(this.comment)) { json.description = this.comment; } Object.getOwnPropertyNames(type).forEach((key) => { const value = type[key]; const number = (0, utils_1.isNumber)(value); if ((number && Number.isFinite(value)) || !number) { (0, utils_1.setProperty)(json, key, value); } }); if (typeof this.default !== 'undefined') { json.default = this.default; } if (this.datatype.datatype === 'uuid') { delete json.default; } return json; } } exports.Column = Column;