UNPKG

sql-ddl-to-json-schema

Version:

Parse and convert SQL DDL statements to a JSON Schema.

111 lines (110 loc) 3.16 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Database = void 0; const create_table_1 = require("./rules/create-table"); const create_index_1 = require("./rules/create-index"); const alter_table_1 = require("./rules/alter-table"); const rename_table_1 = require("./rules/rename-table"); const drop_table_1 = require("./rules/drop-table"); const drop_index_1 = require("./rules/drop-index"); /** * Database, which contains DDS array as its json.def. * It is a formatter for MAIN parser rule. */ class Database { ddsCollection = []; tables = []; /** * Get tables from parsed DDS array. */ getTables() { return this.tables; } /** * Setter for tables. * * @param tables Updated tables. */ setTables(tables) { this.tables = tables; } /** * Get table with given name. * * @param name Table name. */ getTable(name) { return this.tables.find((t) => t.name === name); } /** * Pushes a table to database. * * @param table Table to be added. */ pushTable(table) { /** * Do not add table with same name. */ if (this.tables.some((t) => t.name === table.name)) { return; } this.tables.push(table); } /** * Build tables array from parsed DDL statements by sending them to * appropriate handlers, updating tables array after each statement. * * @param ddsCollection DDS statements array. */ parseDdsCollection(ddsCollection) { this.ddsCollection = ddsCollection; this.ddsCollection.forEach((dds) => { /** * Statements such as SET are supported by parser * but are ignored, returning null DDS. */ if (!dds) { return; } const json = dds.def; const handler = Database.getHandler(json.id); /** * There may be other handlers, which will not have * any effect over tables, and should be ignored. * https://github.com/duartealexf/sql-ddl-to-json-schema/issues/41 */ if (!handler) { return; } handler.setDatabase(this); handler.handleDef(json); }); } /** * Get statement handler from json id. * * @param id */ static getHandler(id) { if (id === 'P_CREATE_TABLE') { return new create_table_1.CreateTable(); } if (id === 'P_CREATE_INDEX') { return new create_index_1.CreateIndex(); } if (id === 'P_ALTER_TABLE') { return new alter_table_1.AlterTable(); } if (id === 'P_RENAME_TABLE') { return new rename_table_1.RenameTable(); } if (id === 'P_DROP_TABLE') { return new drop_table_1.DropTable(); } if (id === 'P_DROP_INDEX') { return new drop_index_1.DropIndex(); } return undefined; } } exports.Database = Database;