UNPKG

mysqldump-ddl-parser

Version:

Parse DDL, output JS object.

94 lines (93 loc) 3.28 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const Column_1 = __importDefault(require("./Column")); const ForeignKey_1 = __importDefault(require("./ForeignKey")); class Table { sql; name = ''; columns = []; primaryKey = []; keys = []; foreignKeys = []; constructor(sql, dialect) { this.sql = sql; if (dialect == 'oracle') { this.oracle(sql); } else { this.mysql(sql); } } oracle(sql) { sql .replace(/\r?\n[\t ]+REFERENCES/, ' REFERENCES') .split(/\r?\n/) .forEach((line) => { line = line.trim(); if (/CREATE TABLE/.test(line)) { const parsed = line.match(/"([^]+)"/); if (parsed) { const splited = parsed[1].split(/\./); this.name = splited[splited.length - 1] .replaceAll(/"/g, '') .toLowerCase(); } } else if (/^(\([\t ]*)?"/.test(line)) { this.columns.push(new Column_1.default(line, 'oracle')); } else if (/ FOREIGN KEY /.test(line)) { this.foreignKeys.push(new ForeignKey_1.default(line, 'oracle')); } else if (/PRIMARY KEY/.test(line)) { const parsed = line.match(/PRIMARY KEY.*\(([^)]*)\)/); if (parsed) { this.primaryKey = parsed[1] .split(/,/) .map((c) => c.trim().toLowerCase().replaceAll(/"/g, '')); } } // TODO INDEX }); } mysql(sql) { sql.split(/\r?\n/).forEach((line) => { line = line.trim(); if (/CREATE TABLE/.test(line)) { this.name = (line.match(/`([^`]+)`/)?.at(1) ?? '').toLowerCase(); } else if (/^`/.test(line)) { this.columns.push(new Column_1.default(line, 'mysql')); } else if (/ FOREIGN KEY /.test(line)) { this.foreignKeys.push(new ForeignKey_1.default(line, 'mysql')); } else if (/^PRIMARY KEY/.test(line)) { const parsed = line.match(/\((.*)\)/); if (parsed?.at(1)) { this.primaryKey = parsed ?.at(1) ?.split(/,/) .map((key) => key.replaceAll('`', '')) ?? this.primaryKey; } } else if (/^KEY/.test(line)) { const parsed = line.match(/\((.*)\)/); if (parsed?.at(1)) { const key = parsed ?.at(1) ?.split(/,/) .map((key) => key.replaceAll('`', '').toLowerCase()); if (key) { this.keys.push(key); } } } }); } } exports.default = Table;