New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@dbml/core

Package Overview
Dependencies
Maintainers
1
Versions
72
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@dbml/core - npm Package Compare versions

Comparing version 1.3.1 to 2.0.0-alpha.0

lib/model_structure/dbState.js

336

lib/export/DbmlExporter.js

@@ -10,2 +10,4 @@ "use strict";

var _utils = require("./utils");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

@@ -23,139 +25,6 @@

function DbmlExporter() {
var schema = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
_classCallCheck(this, DbmlExporter);
this.schema = schema;
}
_createClass(DbmlExporter, [{
key: "exportEnums",
value: function exportEnums() {
var enumStrs = this.schema.enums.map(function (_enum) {
return (
/* eslint-disable indent */
"Enum ".concat("\"".concat(_enum.name, "\""), " {\n", _enum.values.map(function (value) {
return " \"".concat(value.name, "\"").concat(value.note ? " [note: '".concat(value.note, "']") : '');
}).join('\n'), "\n}\n")
/* eslint-enable indent */
);
});
return enumStrs.length ? enumStrs.join('\n') : '';
}
}, {
key: "getTableContentArr",
value: function getTableContentArr() {
var tableContentArr = this.schema.tables.map(function (table) {
var name = table.name;
var fieldContents = DbmlExporter.getFieldLines(table);
var indexContents = DbmlExporter.getIndexLines(table);
return {
name: name,
fieldContents: fieldContents,
indexContents: indexContents
};
});
return tableContentArr;
}
}, {
key: "exportTables",
value: function exportTables() {
var tableContentArr = this.getTableContentArr();
var tableStrs = tableContentArr.map(function (table) {
var indexStr = '';
if (!_lodash["default"].isEmpty(table.indexContents)) {
/* eslint-disable indent */
indexStr = "\n \nIndexes {\n".concat(table.indexContents.map(function (indexLine) {
return " ".concat(indexLine);
}).join('\n'), "\n}");
/* eslint-enable indent */
}
/* eslint-disable indent */
var tableStr = "Table \"".concat(table.name, "\" {\n").concat(table.fieldContents.map(function (line) {
return " ".concat(line);
}).join('\n') // format with tab
, "\n").concat(indexStr ? "".concat(indexStr, "\n") : '', "}\n");
/* eslint-enable indent */
return tableStr;
});
return tableStrs.length ? tableStrs.join('\n') : '';
}
}, {
key: "exportRefs",
value: function exportRefs() {
var _this = this;
var validRefs = this.schema.refs.filter(function (ref) {
return ref.endpoints.every(function (endpoint) {
return _this.schema.tables.find(function (table) {
return table.name === endpoint.tableName;
});
});
});
var strArr = validRefs.map(function (ref) {
var refEndpointIndex = ref.endpoints.findIndex(function (endpoint) {
return endpoint.relation === '1';
});
var foreignEndpoint = ref.endpoints[1 - refEndpointIndex];
var refEndpoint = ref.endpoints[refEndpointIndex];
var line = 'Ref';
if (ref.name) {
line += " \"".concat(ref.name, "\"");
}
line += ':';
line += "\"".concat(refEndpoint.tableName, "\".\"").concat(refEndpoint.fieldName, "\" ");
if (foreignEndpoint.relation === '1') line += '- ';else line += '< ';
line += "\"".concat(foreignEndpoint.tableName, "\".\"").concat(foreignEndpoint.fieldName, "\"");
var refActions = [];
if (ref.onUpdate) {
refActions.push("update: ".concat(ref.onUpdate.toLowerCase()));
}
if (ref.onDelete) {
refActions.push("delete: ".concat(ref.onDelete.toLowerCase()));
}
if (refActions.length > 0) {
line += " [".concat(refActions.join(', '), "]");
}
line += '\n';
return line;
});
return strArr.length ? strArr.join('\n') : '';
}
}, {
key: "export",
value: function _export() {
var res = '';
var hasBlockAbove = false;
if (!_lodash["default"].isEmpty(this.schema.enums)) {
res += this.exportEnums();
hasBlockAbove = true;
}
if (!_lodash["default"].isEmpty(this.schema.tables)) {
if (hasBlockAbove) res += '\n';
res += this.exportTables();
hasBlockAbove = true;
}
if (!_lodash["default"].isEmpty(this.schema.refs)) {
if (hasBlockAbove) res += '\n';
res += this.exportRefs();
hasBlockAbove = true;
}
return res;
}
}], [{
_createClass(DbmlExporter, null, [{
key: "hasWhiteSpace",

@@ -171,9 +40,20 @@ value: function hasWhiteSpace(str) {

}, {
key: "exportEnums",
value: function exportEnums(enumIds, model) {
var enumStrs = enumIds.map(function (enumId) {
var _enum = model.enums[enumId];
var schema = model.schemas[_enum.schemaId];
return "Enum ".concat((0, _utils.shouldPrintSchema)(schema, model) ? "\"".concat(schema.name, "\".") : '', "\"").concat(_enum.name, "\" {\n").concat(_enum.valueIds.map(function (valueId) {
return " \"".concat(model.enumValues[valueId].name, "\"").concat(model.enumValues[valueId].note ? " [note: '".concat(model.enumValues[valueId].note, "']") : '');
}).join('\n'), "\n}\n");
});
return enumStrs.length ? enumStrs.join('\n') : '';
}
}, {
key: "getFieldLines",
value: function getFieldLines(table) {
var lines = table.fields.map(function (field) {
/* eslint-disable indent */
value: function getFieldLines(tableId, model) {
var table = model.tables[tableId];
var lines = table.fieldIds.map(function (fieldId) {
var field = model.fields[fieldId];
var line = "\"".concat(field.name, "\" ").concat(DbmlExporter.hasWhiteSpace(field.type.type_name) ? "\"".concat(field.type.type_name, "\"") : field.type.type_name);
/* eslint-enable indent */
var constraints = [];

@@ -235,8 +115,12 @@

key: "getIndexLines",
value: function getIndexLines(table) {
var lines = table.indexes.map(function (index) {
value: function getIndexLines(tableId, model) {
var table = model.tables[tableId];
var lines = table.indexIds.map(function (indexId) {
var line = '';
var index = model.indexes[indexId];
if (index.columns.length > 1) {
line = "(".concat(index.columns.map(function (column) {
if (index.columnIds.length > 1) {
line = "(".concat(index.columnIds.map(function (columnId) {
var column = model.indexColumns[columnId];
if (column.type === 'expression') {

@@ -248,4 +132,5 @@ return "`".concat(column.value, "`");

}).join(', '), ")");
} else if (index.columns.length === 1) {
line = index.columns[0].type === 'expression' ? "`".concat(index.columns[0].value, "`") : index.columns[0].value;
} else if (index.columnIds.length === 1) {
var column = model.indexColumns[index.columnIds[0]];
line = column.type === 'expression' ? "`".concat(column.value, "`") : column.value;
}

@@ -281,2 +166,163 @@

}
}, {
key: "getTableContentArr",
value: function getTableContentArr(tableIds, model) {
var tableContentArr = tableIds.map(function (tableId) {
var fieldContents = DbmlExporter.getFieldLines(tableId, model);
var indexContents = DbmlExporter.getIndexLines(tableId, model);
return {
tableId: tableId,
fieldContents: fieldContents,
indexContents: indexContents
};
});
return tableContentArr;
}
}, {
key: "getTableSettings",
value: function getTableSettings(table) {
var settingStr = '';
var settingSep = ', ';
if (table.headerColor) {
settingStr += "headerColor: ".concat(table.headerColor).concat(settingSep);
}
if (table.note) {
settingStr += "note: '".concat(table.note, "'").concat(settingSep);
}
if (settingStr.endsWith(', ')) {
settingStr = settingStr.replace(/,\s$/, '');
}
return settingStr ? " [".concat(settingStr, "]") : '';
}
}, {
key: "exportTables",
value: function exportTables(tableIds, model) {
var _this = this;
var tableContentArr = DbmlExporter.getTableContentArr(tableIds, model);
var tableStrs = tableContentArr.map(function (tableContent) {
var table = model.tables[tableContent.tableId];
var schema = model.schemas[table.schemaId];
var tableSettingStr = _this.getTableSettings(table);
var indexStr = '';
if (!_lodash["default"].isEmpty(tableContent.indexContents)) {
indexStr = "\nIndexes {\n".concat(tableContent.indexContents.map(function (indexLine) {
return " ".concat(indexLine);
}).join('\n'), "\n}");
}
var tableStr = "Table ".concat((0, _utils.shouldPrintSchema)(schema, model) ? "\"".concat(schema.name, "\".") : '', "\"").concat(table.name, "\"").concat(tableSettingStr, " {\n").concat(tableContent.fieldContents.map(function (line) {
return " ".concat(line);
}).join('\n'), "\n").concat(indexStr ? "".concat(indexStr, "\n") : '', "}\n");
return tableStr;
});
return tableStrs.length ? tableStrs.join('\n') : '';
}
}, {
key: "exportRefs",
value: function exportRefs(refIds, model) {
var strArr = refIds.map(function (refId) {
var ref = model.refs[refId];
var refEndpointIndex = ref.endpointIds.findIndex(function (endpointId) {
return model.endpoints[endpointId].relation === '1';
});
var foreignEndpointId = ref.endpointIds[1 - refEndpointIndex];
var refEndpointId = ref.endpointIds[refEndpointIndex];
var foreignEndpoint = model.endpoints[foreignEndpointId];
var refEndpoint = model.endpoints[refEndpointId];
var line = 'Ref';
var refEndpointField = model.fields[refEndpoint.fieldId];
var refEndpointTable = model.tables[refEndpointField.tableId];
var refEndpointSchema = model.schemas[refEndpointTable.schemaId];
if (ref.name) {
line += " ".concat((0, _utils.shouldPrintSchema)(model.schemas[ref.schemaId], model) ? "\"".concat(model.schemas[ref.schemaId].name, "\".") : '', "\"").concat(ref.name, "\"");
}
line += ':';
line += "".concat((0, _utils.shouldPrintSchema)(refEndpointSchema, model) ? "\"".concat(refEndpointSchema.name, "\".") : '', "\"").concat(refEndpointTable.name, "\".\"").concat(refEndpointField.name, "\" ");
var foreignEndpointField = model.fields[foreignEndpoint.fieldId];
var foreignEndpointTable = model.tables[foreignEndpointField.tableId];
var foreignEndpointSchema = model.schemas[foreignEndpointTable.schemaId];
if (foreignEndpoint.relation === '1') line += '- ';else line += '< ';
line += "".concat((0, _utils.shouldPrintSchema)(foreignEndpointSchema, model) ? "\"".concat(foreignEndpointSchema.name, "\".") : '', "\"").concat(foreignEndpointTable.name, "\".\"").concat(foreignEndpointField.name, "\"");
var refActions = [];
if (ref.onUpdate) {
refActions.push("update: ".concat(ref.onUpdate.toLowerCase()));
}
if (ref.onDelete) {
refActions.push("delete: ".concat(ref.onDelete.toLowerCase()));
}
if (refActions.length > 0) {
line += " [".concat(refActions.join(', '), "]");
}
line += '\n';
return line;
});
return strArr.length ? strArr.join('\n') : '';
}
}, {
key: "exportTableGroups",
value: function exportTableGroups(tableGroupIds, model) {
var tableGroupStrs = tableGroupIds.map(function (groupId) {
var group = model.tableGroups[groupId];
var groupSchema = model.schemas[group.schemaId];
return "TableGroup ".concat((0, _utils.shouldPrintSchema)(groupSchema, model) ? "\"".concat(groupSchema.name, "\".") : '', "\"").concat(group.name, "\" {\n").concat(group.tableIds.map(function (tableId) {
var table = model.tables[tableId];
var tableSchema = model.schemas[table.schemaId];
return " ".concat((0, _utils.shouldPrintSchema)(tableSchema, model) ? "\"".concat(tableSchema.name, "\".") : '', "\"").concat(table.name, "\"");
}).join('\n'), "\n}\n");
});
return tableGroupStrs.length ? tableGroupStrs.join('\n') : '';
}
}, {
key: "export",
value: function _export(model) {
var res = '';
var hasBlockAbove = false;
var database = model.database['1'];
database.schemaIds.forEach(function (schemaId) {
var _model$schemas$schema = model.schemas[schemaId],
enumIds = _model$schemas$schema.enumIds,
tableIds = _model$schemas$schema.tableIds,
tableGroupIds = _model$schemas$schema.tableGroupIds,
refIds = _model$schemas$schema.refIds;
if (!_lodash["default"].isEmpty(enumIds)) {
if (hasBlockAbove) res += '\n';
res += DbmlExporter.exportEnums(enumIds, model);
hasBlockAbove = true;
}
if (!_lodash["default"].isEmpty(tableIds)) {
if (hasBlockAbove) res += '\n';
res += DbmlExporter.exportTables(tableIds, model);
hasBlockAbove = true;
}
if (!_lodash["default"].isEmpty(tableGroupIds)) {
if (hasBlockAbove) res += '\n';
res += DbmlExporter.exportTableGroups(tableGroupIds, model);
hasBlockAbove = true;
}
if (!_lodash["default"].isEmpty(refIds)) {
if (hasBlockAbove) res += '\n';
res += DbmlExporter.exportRefs(refIds, model);
hasBlockAbove = true;
}
});
return res;
}
}]);

@@ -283,0 +329,0 @@

@@ -8,3 +8,3 @@ "use strict";

var _SchemaExporter = _interopRequireDefault(require("./SchemaExporter"));
var _ModelExporter = _interopRequireDefault(require("./ModelExporter"));

@@ -16,6 +16,5 @@ var _Parser = _interopRequireDefault(require("../parse/Parser"));

function _export(str, format) {
var parser = new _Parser["default"]();
var schema = parser.parse(str, 'dbml');
var exporter = new _SchemaExporter["default"](schema);
return exporter["export"](format);
var database = _Parser["default"].parse(str, 'dbml');
return _ModelExporter["default"]["export"](database.normalize(), format);
}

@@ -22,0 +21,0 @@

@@ -8,8 +8,2 @@ "use strict";

var _Exporter2 = _interopRequireDefault(require("./Exporter"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

@@ -21,29 +15,19 @@

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var JsonExporter =
/*#__PURE__*/
function (_Exporter) {
_inherits(JsonExporter, _Exporter);
function () {
function JsonExporter() {
var schema = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
_classCallCheck(this, JsonExporter);
return _possibleConstructorReturn(this, _getPrototypeOf(JsonExporter).call(this, schema));
}
_createClass(JsonExporter, [{
_createClass(JsonExporter, null, [{
key: "export",
value: function _export() {
return JSON.stringify(this.schema["export"](), null, 2);
value: function _export(model) {
var isNormalized = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
if (!isNormalized) {
return JSON.stringify(model["export"](), null, 2);
}
return JSON.stringify(model, null, 2);
}

@@ -53,5 +37,5 @@ }]);

return JsonExporter;
}(_Exporter2["default"]);
}();
var _default = JsonExporter;
exports["default"] = _default;

@@ -10,8 +10,6 @@ "use strict";

var _Exporter2 = _interopRequireDefault(require("./Exporter"));
var _utils = require("./utils");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }

@@ -31,40 +29,102 @@

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
var MySQLExporter =
/*#__PURE__*/
function () {
function MySQLExporter() {
_classCallCheck(this, MySQLExporter);
}
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
_createClass(MySQLExporter, null, [{
key: "getFieldLines",
value: function getFieldLines(tableId, model) {
var table = model.tables[tableId];
var lines = table.fieldIds.map(function (fieldId) {
var field = model.fields[fieldId];
var line = '';
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
if (field.enumId) {
var _enum = model.enums[field.enumId];
line = "`".concat(field.name, "` ENUM (");
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
var enumValues = _enum.valueIds.map(function (valueId) {
return "'".concat(model.enumValues[valueId].name, "'");
});
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
line += "".concat(enumValues.join(', '), ")");
} else {
line = "`".concat(field.name, "` ").concat(field.type.type_name !== 'varchar' ? field.type.type_name : 'varchar(255)');
}
var MySQLExporter =
/*#__PURE__*/
function (_Exporter) {
_inherits(MySQLExporter, _Exporter);
if (field.unique) {
line += ' UNIQUE';
}
function MySQLExporter() {
var _this;
if (field.pk) {
line += ' PRIMARY KEY';
}
var schema = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
if (field.not_null) {
line += ' NOT NULL';
}
_classCallCheck(this, MySQLExporter);
if (field.increment) {
line += ' AUTO_INCREMENT';
}
_this = _possibleConstructorReturn(this, _getPrototypeOf(MySQLExporter).call(this, schema));
_this.indexes = _Exporter2["default"].getIndexesFromSchema(schema);
return _this;
}
if (field.dbdefault) {
if (field.dbdefault.type === 'expression') {
line += " DEFAULT (".concat(field.dbdefault.value, ")");
} else if (field.dbdefault.type === 'string') {
line += " DEFAULT \"".concat(field.dbdefault.value, "\"");
} else {
line += " DEFAULT ".concat(field.dbdefault.value);
}
}
_createClass(MySQLExporter, [{
if (field.note) {
line += " COMMENT '".concat(field.note, "'");
}
return line;
});
return lines;
}
}, {
key: "getCompositePKs",
value: function getCompositePKs(tableId, model) {
var table = model.tables[tableId];
var compositePkIds = table.indexIds ? table.indexIds.filter(function (indexId) {
return model.indexes[indexId].pk;
}) : [];
var lines = compositePkIds.map(function (keyId) {
var key = model.indexes[keyId];
var line = 'PRIMARY KEY';
var columnArr = [];
key.columnIds.forEach(function (columnId) {
var column = model.indexColumns[columnId];
var columnStr = '';
if (column.type === 'expression') {
columnStr = "(".concat(column.value, ")");
} else {
columnStr = "`".concat(column.value, "`");
}
columnArr.push(columnStr);
});
line += " (".concat(columnArr.join(', '), ")");
return line;
});
return lines;
}
}, {
key: "getTableContentArr",
value: function getTableContentArr() {
var tableContentArr = this.schema.tables.map(function (table) {
var name = table.name;
var fieldContents = MySQLExporter.getFieldLines(table);
var primaryCompositeKey = MySQLExporter.getPrimaryCompositeKey(table);
value: function getTableContentArr(tableIds, model) {
var tableContentArr = tableIds.map(function (tableId) {
var fieldContents = MySQLExporter.getFieldLines(tableId, model);
var compositePKs = MySQLExporter.getCompositePKs(tableId, model);
return {
name: name,
tableId: tableId,
fieldContents: fieldContents,
primaryCompositeKey: primaryCompositeKey
compositePKs: compositePKs
};

@@ -76,14 +136,11 @@ });

key: "exportTables",
value: function exportTables() {
var tableContentArr = this.getTableContentArr();
var tableStrs = tableContentArr.map(function (table) {
var content = [].concat(_toConsumableArray(table.fieldContents), _toConsumableArray(table.primaryCompositeKey));
/* eslint-disable indent */
var tableStr = "CREATE TABLE `".concat(table.name, "` (\n").concat(content.map(function (line) {
value: function exportTables(tableIds, model) {
var tableContentArr = MySQLExporter.getTableContentArr(tableIds, model);
var tableStrs = tableContentArr.map(function (tableContent) {
var content = [].concat(_toConsumableArray(tableContent.fieldContents), _toConsumableArray(tableContent.compositePKs));
var table = model.tables[tableContent.tableId];
var schema = model.schemas[table.schemaId];
var tableStr = "CREATE TABLE ".concat((0, _utils.shouldPrintSchema)(schema, model) ? "`".concat(schema.name, "`.") : '', "`").concat(table.name, "` (\n").concat(content.map(function (line) {
return " ".concat(line);
}).join(',\n') // format with tab
, "\n);\n");
/* eslint-enable indent */
}).join(',\n'), "\n);\n");
return tableStr;

@@ -95,19 +152,19 @@ });

key: "exportRefs",
value: function exportRefs() {
var _this2 = this;
var validRefs = this.schema.refs.filter(function (ref) {
return ref.endpoints.every(function (endpoint) {
return _this2.schema.tables.find(function (table) {
return table.name === endpoint.tableName;
});
value: function exportRefs(refIds, model) {
var strArr = refIds.map(function (refId) {
var ref = model.refs[refId];
var refEndpointIndex = ref.endpointIds.findIndex(function (endpointId) {
return model.endpoints[endpointId].relation === '1';
});
});
var strArr = validRefs.map(function (ref) {
var refEndpointIndex = ref.endpoints.findIndex(function (endpoint) {
return endpoint.relation === '1';
});
var foreignEndpoint = ref.endpoints[1 - refEndpointIndex];
var refEndpoint = ref.endpoints[refEndpointIndex];
var line = "ALTER TABLE `".concat(foreignEndpoint.tableName, "` ADD ");
var foreignEndpointId = ref.endpointIds[1 - refEndpointIndex];
var refEndpointId = ref.endpointIds[refEndpointIndex];
var foreignEndpoint = model.endpoints[foreignEndpointId];
var refEndpoint = model.endpoints[refEndpointId];
var refEndpointField = model.fields[refEndpoint.fieldId];
var refEndpointTable = model.tables[refEndpointField.tableId];
var refEndpointSchema = model.schemas[refEndpointTable.schemaId];
var foreignEndpointField = model.fields[foreignEndpoint.fieldId];
var foreignEndpointTable = model.tables[foreignEndpointField.tableId];
var foreignEndpointSchema = model.schemas[foreignEndpointTable.schemaId];
var line = "ALTER TABLE ".concat((0, _utils.shouldPrintSchema)(foreignEndpointSchema, model) ? "`".concat(foreignEndpointSchema.name, "`.") : '', "`").concat(foreignEndpointTable.name, "` ADD ");

@@ -118,3 +175,3 @@ if (ref.name) {

line += "FOREIGN KEY (`".concat(foreignEndpoint.fieldName, "`) REFERENCES `").concat(refEndpoint.tableName, "` (`").concat(refEndpoint.fieldName, "`)");
line += "FOREIGN KEY (`".concat(foreignEndpointField.name, "`) REFERENCES ").concat((0, _utils.shouldPrintSchema)(refEndpointSchema, model) ? "`".concat(refEndpointSchema.name, "`.") : '', "`").concat(refEndpointTable.name, "` (`").concat(refEndpointField.name, "`)");

@@ -136,4 +193,10 @@ if (ref.onDelete) {

key: "exportIndexes",
value: function exportIndexes() {
var indexArr = this.indexes.map(function (index, i) {
value: function exportIndexes(indexIds, model) {
// exclude composite pk index
var indexArr = indexIds.filter(function (indexId) {
return !model.indexes[indexId].pk;
}).map(function (indexId, i) {
var index = model.indexes[indexId];
var table = model.tables[index.tableId];
var schema = model.schemas[table.schemaId];
var line = 'CREATE';

@@ -145,6 +208,7 @@

var indexName = index.name ? "`".concat(index.name, "`") : "`".concat(index.table.name, "_index_").concat(i, "`");
line += " INDEX ".concat(indexName, " ON `").concat(index.table.name, "`");
var indexName = index.name ? "`".concat(index.name, "`") : "`".concat((0, _utils.shouldPrintSchema)(schema, model) ? "`".concat(schema.name, "`.") : '').concat(table.name, "_index_").concat(i, "`");
line += " INDEX ".concat(indexName, " ON ").concat((0, _utils.shouldPrintSchema)(schema, model) ? "`".concat(schema.name, "`.") : '', "`").concat(table.name, "`");
var columnArr = [];
index.columns.forEach(function (column) {
index.columnIds.forEach(function (columnId) {
var column = model.indexColumns[columnId];
var columnStr = '';

@@ -173,99 +237,42 @@

key: "export",
value: function _export() {
value: function _export(model) {
var res = '';
var hasBlockAbove = false;
var database = model.database['1'];
var indexIds = [];
database.schemaIds.forEach(function (schemaId) {
var schema = model.schemas[schemaId];
var tableIds = schema.tableIds,
refIds = schema.refIds;
if (!_lodash["default"].isEmpty(this.schema.tables)) {
res += this.exportTables();
hasBlockAbove = true;
}
if (!_lodash["default"].isEmpty(this.schema.refs)) {
if (hasBlockAbove) res += '\n';
res += this.exportRefs();
hasBlockAbove = true;
}
if (!_lodash["default"].isEmpty(this.indexes)) {
if (hasBlockAbove) res += '\n';
res += this.exportIndexes();
hasBlockAbove = true;
}
return res;
}
}], [{
key: "getFieldLines",
value: function getFieldLines(table) {
var lines = table.fields.map(function (field) {
var line = '';
if (field.enumRef) {
line = "`".concat(field.name, "` ENUM (");
var enumValues = field.enumRef.values.map(function (value) {
return "'".concat(value.name, "'");
});
line += "".concat(enumValues.join(', '), ")");
} else {
line = "`".concat(field.name, "` ").concat(field.type.type_name !== 'varchar' ? field.type.type_name : 'varchar(255)');
if ((0, _utils.shouldPrintSchema)(schema, model)) {
if (hasBlockAbove) res += '\n';
res += "CREATE DATABASE `".concat(schema.name, "`;\n");
hasBlockAbove = true;
}
if (field.unique) {
line += ' UNIQUE';
if (!_lodash["default"].isEmpty(tableIds)) {
if (hasBlockAbove) res += '\n';
res += MySQLExporter.exportTables(tableIds, model);
hasBlockAbove = true;
}
if (field.pk) {
line += ' PRIMARY KEY';
if (!_lodash["default"].isEmpty(refIds)) {
if (hasBlockAbove) res += '\n';
res += MySQLExporter.exportRefs(refIds, model);
hasBlockAbove = true;
}
if (field.not_null) {
line += ' NOT NULL';
}
if (field.increment) {
line += ' AUTO_INCREMENT';
}
if (field.dbdefault) {
if (field.dbdefault.type === 'expression') {
line += " DEFAULT (".concat(field.dbdefault.value, ")");
} else if (field.dbdefault.type === 'string') {
line += " DEFAULT \"".concat(field.dbdefault.value, "\"");
} else {
line += " DEFAULT ".concat(field.dbdefault.value);
}
}
if (field.note) {
line += " COMMENT '".concat(field.note, "'");
}
return line;
indexIds.push.apply(indexIds, _toConsumableArray(_lodash["default"].flatten(tableIds.map(function (tableId) {
return model.tables[tableId].indexIds;
}))));
});
return lines;
}
}, {
key: "getPrimaryCompositeKey",
value: function getPrimaryCompositeKey(table) {
var primaryCompositeKey = table.indexes ? table.indexes.filter(function (index) {
return index.pk;
}) : [];
var lines = primaryCompositeKey.map(function (key) {
var line = 'PRIMARY KEY';
var columnArr = [];
key.columns.forEach(function (column) {
var columnStr = '';
if (column.type === 'expression') {
columnStr = "(".concat(column.value, ")");
} else {
columnStr = "`".concat(column.value, "`");
}
if (!_lodash["default"].isEmpty(indexIds)) {
if (hasBlockAbove) res += '\n';
res += MySQLExporter.exportIndexes(indexIds, model);
hasBlockAbove = true;
}
columnArr.push(columnStr);
});
line += " (".concat(columnArr.join(', '), ")");
return line;
});
return lines;
return res;
}

@@ -275,5 +282,5 @@ }]);

return MySQLExporter;
}(_Exporter2["default"]);
}();
var _default = MySQLExporter;
exports["default"] = _default;

@@ -10,8 +10,6 @@ "use strict";

var _Exporter2 = _interopRequireDefault(require("./Exporter"));
var _utils = require("./utils");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }

@@ -31,35 +29,18 @@

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var PostgresExporter =
/*#__PURE__*/
function (_Exporter) {
_inherits(PostgresExporter, _Exporter);
function () {
function PostgresExporter() {
var _this;
var schema = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
_classCallCheck(this, PostgresExporter);
_this = _possibleConstructorReturn(this, _getPrototypeOf(PostgresExporter).call(this, schema));
_this.indexes = _Exporter2["default"].getIndexesFromSchema(schema);
_this.comments = _Exporter2["default"].getCommentsFromSchema(schema);
return _this;
}
_createClass(PostgresExporter, [{
_createClass(PostgresExporter, null, [{
key: "exportEnums",
value: function exportEnums() {
var enumArr = this.schema.enums.map(function (_enum) {
var enumValueArr = _enum.values.map(function (value) {
value: function exportEnums(enumIds, model) {
var enumArr = enumIds.map(function (enumId) {
var _enum = model.enums[enumId];
var schema = model.schemas[_enum.schemaId];
var enumValueArr = _enum.valueIds.map(function (valueId) {
var value = model.enumValues[valueId];
return " '".concat(value.name, "'");

@@ -69,3 +50,3 @@ });

var enumValueStr = enumValueArr.join(',\n');
var line = "CREATE TYPE \"".concat(_enum.name, "\" AS ENUM (\n").concat(enumValueStr, "\n);\n");
var line = "CREATE TYPE ".concat((0, _utils.shouldPrintSchema)(schema, model) ? "\"".concat(schema.name, "\".") : '', "\"").concat(_enum.name, "\" AS ENUM (\n").concat(enumValueStr, "\n);\n");
return line;

@@ -76,12 +57,81 @@ });

}, {
key: "getFieldLines",
value: function getFieldLines(tableId, model) {
var table = model.tables[tableId];
var lines = table.fieldIds.map(function (fieldId) {
var field = model.fields[fieldId];
var line = '';
if (field.increment) {
line = "\"".concat(field.name, "\" SERIAL");
} else if ((0, _utils.hasWhiteSpace)(field.type.type_name)) {
line = "\"".concat(field.name, "\" \"").concat(field.type.type_name, "\"");
} else {
line = "\"".concat(field.name, "\" ").concat(field.type.type_name);
}
if (field.unique) {
line += ' UNIQUE';
}
if (field.pk) {
line += ' PRIMARY KEY';
}
if (field.not_null) {
line += ' NOT NULL';
}
if (field.dbdefault) {
if (field.dbdefault.type === 'expression') {
line += " DEFAULT (".concat(field.dbdefault.value, ")");
} else if (field.dbdefault.type === 'string') {
line += " DEFAULT '".concat(field.dbdefault.value, "'");
} else {
line += " DEFAULT ".concat(field.dbdefault.value);
}
}
return line;
});
return lines;
}
}, {
key: "getCompositePKs",
value: function getCompositePKs(tableId, model) {
var table = model.tables[tableId];
var compositePkIds = table.indexIds ? table.indexIds.filter(function (indexId) {
return model.indexes[indexId].pk;
}) : [];
var lines = compositePkIds.map(function (keyId) {
var key = model.indexes[keyId];
var line = 'PRIMARY KEY';
var columnArr = [];
key.columnIds.forEach(function (columnId) {
var column = model.indexColumns[columnId];
var columnStr = '';
if (column.type === 'expression') {
columnStr = "(".concat(column.value, ")");
} else {
columnStr = "\"".concat(column.value, "\"");
}
columnArr.push(columnStr);
});
line += " (".concat(columnArr.join(', '), ")");
return line;
});
return lines;
}
}, {
key: "getTableContentArr",
value: function getTableContentArr() {
var tableContentArr = this.schema.tables.map(function (table) {
var name = table.name;
var fieldContents = PostgresExporter.getFieldLines(table);
var primaryCompositeKey = PostgresExporter.getPrimaryCompositeKey(table);
value: function getTableContentArr(tableIds, model) {
var tableContentArr = tableIds.map(function (tableId) {
var fieldContents = PostgresExporter.getFieldLines(tableId, model);
var compositePKs = PostgresExporter.getCompositePKs(tableId, model);
return {
name: name,
tableId: tableId,
fieldContents: fieldContents,
primaryCompositeKey: primaryCompositeKey
compositePKs: compositePKs
};

@@ -93,13 +143,11 @@ });

key: "exportTables",
value: function exportTables() {
var tableContentArr = this.getTableContentArr();
var tableStrs = tableContentArr.map(function (table) {
var content = [].concat(_toConsumableArray(table.fieldContents), _toConsumableArray(table.primaryCompositeKey));
/* eslint-disable indent */
var tableStr = "CREATE TABLE \"".concat(table.name, "\" (\n").concat(content.map(function (line) {
value: function exportTables(tableIds, model) {
var tableContentArr = PostgresExporter.getTableContentArr(tableIds, model);
var tableStrs = tableContentArr.map(function (tableContent) {
var content = [].concat(_toConsumableArray(tableContent.fieldContents), _toConsumableArray(tableContent.compositePKs));
var table = model.tables[tableContent.tableId];
var schema = model.schemas[table.schemaId];
var tableStr = "CREATE TABLE ".concat((0, _utils.shouldPrintSchema)(schema, model) ? "\"".concat(schema.name, "\".") : '', "\"").concat(table.name, "\" (\n").concat(content.map(function (line) {
return " ".concat(line);
}).join(',\n'), "\n);\n");
/* eslint-enable indent */
return tableStr;

@@ -111,19 +159,19 @@ });

key: "exportRefs",
value: function exportRefs() {
var _this2 = this;
var validRefs = this.schema.refs.filter(function (ref) {
return ref.endpoints.every(function (endpoint) {
return _this2.schema.tables.find(function (table) {
return table.name === endpoint.tableName;
});
value: function exportRefs(refIds, model) {
var strArr = refIds.map(function (refId) {
var ref = model.refs[refId];
var refEndpointIndex = ref.endpointIds.findIndex(function (endpointId) {
return model.endpoints[endpointId].relation === '1';
});
});
var strArr = validRefs.map(function (ref) {
var refEndpointIndex = ref.endpoints.findIndex(function (endpoint) {
return endpoint.relation === '1';
});
var foreignEndpoint = ref.endpoints[1 - refEndpointIndex];
var refEndpoint = ref.endpoints[refEndpointIndex];
var line = "ALTER TABLE \"".concat(foreignEndpoint.tableName, "\" ADD ");
var foreignEndpointId = ref.endpointIds[1 - refEndpointIndex];
var refEndpointId = ref.endpointIds[refEndpointIndex];
var foreignEndpoint = model.endpoints[foreignEndpointId];
var refEndpoint = model.endpoints[refEndpointId];
var refEndpointField = model.fields[refEndpoint.fieldId];
var refEndpointTable = model.tables[refEndpointField.tableId];
var refEndpointSchema = model.schemas[refEndpointTable.schemaId];
var foreignEndpointField = model.fields[foreignEndpoint.fieldId];
var foreignEndpointTable = model.tables[foreignEndpointField.tableId];
var foreignEndpointSchema = model.schemas[foreignEndpointTable.schemaId];
var line = "ALTER TABLE ".concat((0, _utils.shouldPrintSchema)(foreignEndpointSchema, model) ? "\"".concat(foreignEndpointSchema.name, "\".") : '', "\"").concat(foreignEndpointTable.name, "\" ADD ");

@@ -134,3 +182,3 @@ if (ref.name) {

line += "FOREIGN KEY (\"".concat(foreignEndpoint.fieldName, "\") REFERENCES \"").concat(refEndpoint.tableName, "\" (\"").concat(refEndpoint.fieldName, "\")");
line += "FOREIGN KEY (\"".concat(foreignEndpointField.name, "\") REFERENCES ").concat((0, _utils.shouldPrintSchema)(refEndpointSchema, model) ? "\"".concat(refEndpointSchema.name, "\".") : '', "\"").concat(refEndpointTable.name, "\" (\"").concat(refEndpointField.name, "\")");

@@ -152,4 +200,10 @@ if (ref.onDelete) {

key: "exportIndexes",
value: function exportIndexes() {
var indexArr = this.indexes.map(function (index) {
value: function exportIndexes(indexIds, model) {
// exclude composite pk index
var indexArr = indexIds.filter(function (indexId) {
return !model.indexes[indexId].pk;
}).map(function (indexId) {
var index = model.indexes[indexId];
var table = model.tables[index.tableId];
var schema = model.schemas[table.schemaId];
var line = 'CREATE';

@@ -168,3 +222,3 @@

line += " ON \"".concat(index.table.name, "\"");
line += " ON ".concat((0, _utils.shouldPrintSchema)(schema, model) ? "\"".concat(schema.name, "\".") : '', "\"").concat(table.name, "\"");

@@ -176,3 +230,4 @@ if (index.type) {

var columnArr = [];
index.columns.forEach(function (column) {
index.columnIds.forEach(function (columnId) {
var column = model.indexColumns[columnId];
var columnStr = '';

@@ -196,8 +251,11 @@

key: "exportComments",
value: function exportComments() {
var commentArr = this.comments.map(function (comment) {
value: function exportComments(comments, model) {
var commentArr = comments.map(function (comment) {
var line = 'COMMENT ON';
if (comment.type === 'column') {
line += " COLUMN \"".concat(comment.table.name, "\".\"").concat(comment.field.name, "\" IS '").concat(comment.field.note, "'");
var field = model.fields[comment.fieldId];
var table = model.tables[field.tableId];
var schema = model.schemas[table.schemaId];
line += " COLUMN ".concat((0, _utils.shouldPrintSchema)(schema, model) ? "\"".concat(schema.name, "\".") : '', "\"").concat(table.name, "\".\"").concat(field.name, "\" IS '").concat(field.note, "'");
}

@@ -212,32 +270,63 @@

key: "export",
value: function _export() {
value: function _export(model) {
var res = '';
var hasBlockAbove = false;
var database = model.database['1'];
var indexIds = [];
var comments = [];
database.schemaIds.forEach(function (schemaId) {
var schema = model.schemas[schemaId];
var tableIds = schema.tableIds,
enumIds = schema.enumIds,
refIds = schema.refIds;
if (!_lodash["default"].isEmpty(this.schema.enums)) {
res += this.exportEnums();
hasBlockAbove = true;
}
if ((0, _utils.shouldPrintSchema)(schema, model)) {
if (hasBlockAbove) res += '\n';
res += "CREATE SCHEMA \"".concat(schema.name, "\";\n");
hasBlockAbove = true;
}
if (!_lodash["default"].isEmpty(this.schema.tables)) {
if (hasBlockAbove) res += '\n';
res += this.exportTables();
hasBlockAbove = true;
}
if (!_lodash["default"].isEmpty(enumIds)) {
if (hasBlockAbove) res += '\n';
res += PostgresExporter.exportEnums(enumIds, model);
hasBlockAbove = true;
}
if (!_lodash["default"].isEmpty(this.schema.refs)) {
if (hasBlockAbove) res += '\n';
res += this.exportRefs();
hasBlockAbove = true;
}
if (!_lodash["default"].isEmpty(tableIds)) {
if (hasBlockAbove) res += '\n';
res += PostgresExporter.exportTables(tableIds, model);
hasBlockAbove = true;
}
if (!_lodash["default"].isEmpty(this.indexes)) {
if (!_lodash["default"].isEmpty(refIds)) {
if (hasBlockAbove) res += '\n';
res += PostgresExporter.exportRefs(refIds, model);
hasBlockAbove = true;
}
indexIds.push.apply(indexIds, _toConsumableArray(_lodash["default"].flatten(tableIds.map(function (tableId) {
return model.tables[tableId].indexIds;
}))));
comments.push.apply(comments, _toConsumableArray(_lodash["default"].flatten(tableIds.map(function (tableId) {
var fieldIds = model.tables[tableId].fieldIds;
return fieldIds.filter(function (fieldId) {
return model.fields[fieldId].note;
}).map(function (fieldId) {
return {
type: 'column',
fieldId: fieldId
};
});
}))));
});
if (!_lodash["default"].isEmpty(indexIds)) {
if (hasBlockAbove) res += '\n';
res += this.exportIndexes();
res += PostgresExporter.exportIndexes(indexIds, model);
hasBlockAbove = true;
}
if (!_lodash["default"].isEmpty(this.comments)) {
if (!_lodash["default"].isEmpty(comments)) {
if (hasBlockAbove) res += '\n';
res += this.exportComments();
res += PostgresExporter.exportComments(comments, model);
hasBlockAbove = true;

@@ -248,73 +337,8 @@ }

}
}], [{
key: "getFieldLines",
value: function getFieldLines(table) {
var lines = table.fields.map(function (field) {
var line = '';
if (field.increment) {
line = "\"".concat(field.name, "\" SERIAL");
} else if (_Exporter2["default"].hasWhiteSpace(field.type.type_name)) {
line = "\"".concat(field.name, "\" \"").concat(field.type.type_name, "\"");
} else {
line = "\"".concat(field.name, "\" ").concat(field.type.type_name);
}
if (field.unique) {
line += ' UNIQUE';
}
if (field.pk) {
line += ' PRIMARY KEY';
}
if (field.not_null) {
line += ' NOT NULL';
}
if (field.dbdefault) {
if (field.dbdefault.type === 'expression') {
line += " DEFAULT (".concat(field.dbdefault.value, ")");
} else if (field.dbdefault.type === 'string') {
line += " DEFAULT '".concat(field.dbdefault.value, "'");
} else {
line += " DEFAULT ".concat(field.dbdefault.value);
}
}
return line;
});
return lines;
}
}, {
key: "getPrimaryCompositeKey",
value: function getPrimaryCompositeKey(table) {
var primaryCompositeKey = table.indexes ? table.indexes.filter(function (index) {
return index.pk;
}) : [];
var lines = primaryCompositeKey.map(function (key) {
var line = 'PRIMARY KEY';
var columnArr = [];
key.columns.forEach(function (column) {
var columnStr = '';
if (column.type === 'expression') {
columnStr = "(".concat(column.value, ")");
} else {
columnStr = "\"".concat(column.value, "\"");
}
columnArr.push(columnStr);
});
line += " (".concat(columnArr.join(', '), ")");
return line;
});
return lines;
}
}]);
return PostgresExporter;
}(_Exporter2["default"]);
}();
var _default = PostgresExporter;
exports["default"] = _default;

@@ -10,8 +10,6 @@ "use strict";

var _Exporter2 = _interopRequireDefault(require("./Exporter"));
var _utils = require("./utils");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }

@@ -31,40 +29,99 @@

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
var SqlServerExporter =
/*#__PURE__*/
function () {
function SqlServerExporter() {
_classCallCheck(this, SqlServerExporter);
}
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
_createClass(SqlServerExporter, null, [{
key: "getFieldLines",
value: function getFieldLines(tableId, model) {
var table = model.tables[tableId];
var lines = table.fieldIds.map(function (fieldId) {
var field = model.fields[fieldId];
var line = '';
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
if (field.enumId) {
var _enum = model.enums[field.enumId];
line = "[".concat(field.name, "] nvarchar(255) NOT NULL CHECK ([").concat(field.name, "] IN (");
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
var enumValues = _enum.valueIds.map(function (valueId) {
var value = model.enumValues[valueId];
return "'".concat(value.name, "'");
});
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
line += "".concat(enumValues.join(', '), "))");
} else {
line = "[".concat(field.name, "] ").concat(field.type.type_name !== 'varchar' ? field.type.type_name : 'nvarchar(255)');
}
var SqlServerExporter =
/*#__PURE__*/
function (_Exporter) {
_inherits(SqlServerExporter, _Exporter);
if (field.unique) {
line += ' UNIQUE';
}
function SqlServerExporter() {
var _this;
if (field.pk) {
line += ' PRIMARY KEY';
}
var schema = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
if (field.not_null) {
line += ' NOT NULL';
}
_classCallCheck(this, SqlServerExporter);
if (field.increment) {
line += ' IDENTITY(1, 1)';
}
_this = _possibleConstructorReturn(this, _getPrototypeOf(SqlServerExporter).call(this, schema));
_this.indexes = _Exporter2["default"].getIndexesFromSchema(schema);
return _this;
}
if (field.dbdefault) {
if (field.dbdefault.type === 'expression') {
line += " DEFAULT (".concat(field.dbdefault.value, ")");
} else if (field.dbdefault.type === 'string') {
line += " DEFAULT '".concat(field.dbdefault.value, "'");
} else {
line += " DEFAULT (".concat(field.dbdefault.value, ")");
}
}
_createClass(SqlServerExporter, [{
return line;
});
return lines;
}
}, {
key: "getCompositePKs",
value: function getCompositePKs(tableId, model) {
var table = model.tables[tableId];
var compositePkIds = table.indexIds ? table.indexIds.filter(function (indexId) {
return model.indexes[indexId].pk;
}) : [];
var lines = compositePkIds.map(function (keyId) {
var key = model.indexes[keyId];
var line = 'PRIMARY KEY';
var columnArr = [];
key.columnIds.forEach(function (columnId) {
var column = model.indexColumns[columnId];
var columnStr = '';
if (column.type === 'expression') {
columnStr = "(".concat(column.value, ")");
} else {
columnStr = "[".concat(column.value, "]");
}
columnArr.push(columnStr);
});
line += " (".concat(columnArr.join(', '), ")");
return line;
});
return lines;
}
}, {
key: "getTableContentArr",
value: function getTableContentArr() {
var tableContentArr = this.schema.tables.map(function (table) {
var name = table.name;
var fieldContents = SqlServerExporter.getFieldLines(table);
var primaryCompositeKey = SqlServerExporter.getPrimaryCompositeKey(table);
value: function getTableContentArr(tableIds, model) {
var tableContentArr = tableIds.map(function (tableId) {
var fieldContents = SqlServerExporter.getFieldLines(tableId, model);
var compositePKs = SqlServerExporter.getCompositePKs(tableId, model);
return {
name: name,
tableId: tableId,
fieldContents: fieldContents,
primaryCompositeKey: primaryCompositeKey
compositePKs: compositePKs
};

@@ -76,14 +133,11 @@ });

key: "exportTables",
value: function exportTables() {
var tableContentArr = this.getTableContentArr();
var tableStrs = tableContentArr.map(function (table) {
var content = [].concat(_toConsumableArray(table.fieldContents), _toConsumableArray(table.primaryCompositeKey));
/* eslint-disable indent */
var tableStr = "CREATE TABLE [".concat(table.name, "] (\n").concat(content.map(function (line) {
value: function exportTables(tableIds, model) {
var tableContentArr = SqlServerExporter.getTableContentArr(tableIds, model);
var tableStrs = tableContentArr.map(function (tableContent) {
var content = [].concat(_toConsumableArray(tableContent.fieldContents), _toConsumableArray(tableContent.compositePKs));
var table = model.tables[tableContent.tableId];
var schema = model.schemas[table.schemaId];
var tableStr = "CREATE TABLE ".concat((0, _utils.shouldPrintSchema)(schema, model) ? "[".concat(schema.name, "].") : '', "[").concat(table.name, "] (\n").concat(content.map(function (line) {
return " ".concat(line);
}).join(',\n') // format with tab
, "\n)\nGO\n");
/* eslint-enable indent */
}).join(',\n'), "\n)\nGO\n");
return tableStr;

@@ -95,19 +149,19 @@ });

key: "exportRefs",
value: function exportRefs() {
var _this2 = this;
var validRefs = this.schema.refs.filter(function (ref) {
return ref.endpoints.every(function (endpoint) {
return _this2.schema.tables.find(function (table) {
return table.name === endpoint.tableName;
});
value: function exportRefs(refIds, model) {
var strArr = refIds.map(function (refId) {
var ref = model.refs[refId];
var refEndpointIndex = ref.endpointIds.findIndex(function (endpointId) {
return model.endpoints[endpointId].relation === '1';
});
});
var strArr = validRefs.map(function (ref) {
var refEndpointIndex = ref.endpoints.findIndex(function (endpoint) {
return endpoint.relation === '1';
});
var foreignEndpoint = ref.endpoints[1 - refEndpointIndex];
var refEndpoint = ref.endpoints[refEndpointIndex];
var line = "ALTER TABLE [".concat(foreignEndpoint.tableName, "] ADD ");
var foreignEndpointId = ref.endpointIds[1 - refEndpointIndex];
var refEndpointId = ref.endpointIds[refEndpointIndex];
var foreignEndpoint = model.endpoints[foreignEndpointId];
var refEndpoint = model.endpoints[refEndpointId];
var refEndpointField = model.fields[refEndpoint.fieldId];
var refEndpointTable = model.tables[refEndpointField.tableId];
var refEndpointSchema = model.schemas[refEndpointTable.schemaId];
var foreignEndpointField = model.fields[foreignEndpoint.fieldId];
var foreignEndpointTable = model.tables[foreignEndpointField.tableId];
var foreignEndpointSchema = model.schemas[foreignEndpointTable.schemaId];
var line = "ALTER TABLE ".concat((0, _utils.shouldPrintSchema)(foreignEndpointSchema, model) ? "[".concat(foreignEndpointSchema.name, "].") : '', "[").concat(foreignEndpointTable.name, "] ADD ");

@@ -118,3 +172,3 @@ if (ref.name) {

line += "FOREIGN KEY ([".concat(foreignEndpoint.fieldName, "]) REFERENCES [").concat(refEndpoint.tableName, "] ([").concat(refEndpoint.fieldName, "])");
line += "FOREIGN KEY ([".concat(foreignEndpointField.name, "]) REFERENCES ").concat((0, _utils.shouldPrintSchema)(refEndpointSchema, model) ? "[".concat(refEndpointSchema.name, "].") : '', "[").concat(refEndpointTable.name, "] ([").concat(refEndpointField.name, "])");

@@ -136,4 +190,10 @@ if (ref.onDelete) {

key: "exportIndexes",
value: function exportIndexes() {
var indexArr = this.indexes.map(function (index, i) {
value: function exportIndexes(indexIds, model) {
// exclude composite pk index
var indexArr = indexIds.filter(function (indexId) {
return !model.indexes[indexId].pk;
}).map(function (indexId, i) {
var index = model.indexes[indexId];
var table = model.tables[index.tableId];
var schema = model.schemas[table.schemaId];
var line = 'CREATE';

@@ -145,6 +205,7 @@

var indexName = index.name ? "[".concat(index.name, "]") : "[".concat(index.table.name, "_index_").concat(i, "]");
line += " INDEX ".concat(indexName, " ON [").concat(index.table.name, "]");
var indexName = index.name ? "[".concat(index.name, "]") : "".concat((0, _utils.shouldPrintSchema)(schema, model) ? "[".concat(schema.name, "].") : '', "[").concat(table.name, "_index_").concat(i, "]");
line += " INDEX ".concat(indexName, " ON ").concat((0, _utils.shouldPrintSchema)(schema, model) ? "[".concat(schema.name, "].") : '', "[").concat(table.name, "]");
var columnArr = [];
index.columns.forEach(function (column) {
index.columnIds.forEach(function (columnId) {
var column = model.indexColumns[columnId];
var columnStr = '';

@@ -167,21 +228,80 @@

}, {
key: "exportComments",
value: function exportComments(comments, model) {
var commentArr = comments.map(function (comment) {
var line = '';
if (comment.type === 'column') {
var field = model.fields[comment.fieldId];
var table = model.tables[field.tableId];
var schema = model.schemas[table.schemaId];
line = 'EXEC sp_addextendedproperty\n';
line += '@name = N\'Column_Description\'\n';
line += "@value = '".concat(field.note, "'\n");
line += "@level0type = N'Schema', @level0name = '".concat((0, _utils.shouldPrintSchema)(schema, model) ? "".concat(schema.name) : 'dbo', "',\n");
line += "@level1type = N'Table', @level1name = '".concat(table.name, "',\n");
line += "@level2type = N'Column', @level2name = '".concat(field.name, "';\n");
}
line += 'GO\n';
return line;
});
return commentArr.length ? commentArr.join('\n') : '';
}
}, {
key: "export",
value: function _export() {
value: function _export(model) {
var res = '';
var hasBlockAbove = false;
var database = model.database['1'];
var indexIds = [];
var comments = [];
database.schemaIds.forEach(function (schemaId) {
var schema = model.schemas[schemaId];
var tableIds = schema.tableIds,
refIds = schema.refIds;
if (!_lodash["default"].isEmpty(this.schema.tables)) {
res += this.exportTables();
hasBlockAbove = true;
}
if ((0, _utils.shouldPrintSchema)(schema, model)) {
if (hasBlockAbove) res += '\n';
res += "CREATE SCHEMA [".concat(schema.name, "];\nGO\n");
hasBlockAbove = true;
}
if (!_lodash["default"].isEmpty(this.schema.refs)) {
if (!_lodash["default"].isEmpty(tableIds)) {
if (hasBlockAbove) res += '\n';
res += SqlServerExporter.exportTables(tableIds, model);
hasBlockAbove = true;
}
if (!_lodash["default"].isEmpty(refIds)) {
if (hasBlockAbove) res += '\n';
res += SqlServerExporter.exportRefs(refIds, model);
hasBlockAbove = true;
}
indexIds.push.apply(indexIds, _toConsumableArray(_lodash["default"].flatten(tableIds.map(function (tableId) {
return model.tables[tableId].indexIds;
}))));
comments.push.apply(comments, _toConsumableArray(_lodash["default"].flatten(tableIds.map(function (tableId) {
var fieldIds = model.tables[tableId].fieldIds;
return fieldIds.filter(function (fieldId) {
return model.fields[fieldId].note;
}).map(function (fieldId) {
return {
type: 'column',
fieldId: fieldId
};
});
}))));
});
if (!_lodash["default"].isEmpty(indexIds)) {
if (hasBlockAbove) res += '\n';
res += this.exportRefs();
res += SqlServerExporter.exportIndexes(indexIds, model);
hasBlockAbove = true;
}
if (!_lodash["default"].isEmpty(this.indexes)) {
if (!_lodash["default"].isEmpty(comments)) {
if (hasBlockAbove) res += '\n';
res += this.exportIndexes();
res += SqlServerExporter.exportComments(comments, model);
hasBlockAbove = true;

@@ -192,90 +312,8 @@ }

}
}], [{
key: "getFieldLines",
value: function getFieldLines(table) {
var lines = table.fields.map(function (field) {
var line = '';
if (field.enumRef) {
line = "[".concat(field.name, "] nvarchar(255) NOT NULL CHECK ([").concat(field.name, "] IN (");
var enumValues = field.enumRef.values.map(function (value) {
return "'".concat(value.name, "'");
});
line += "".concat(enumValues.join(', '), "))");
} else {
line = "[".concat(field.name, "] ").concat(field.type.type_name !== 'varchar' ? field.type.type_name : 'nvarchar(255)');
line = line.replace(/boolean/gi, 'BIT'); // SQL Server does not have type BOOLEAN
// line = line.replace(/char|varchar|nvarchar/gi, '[$&]');
}
if (field.unique) {
line += ' UNIQUE';
}
if (field.pk) {
line += ' PRIMARY KEY';
}
if (!field.enumRef && field.not_null) {
line += ' NOT NULL';
}
if (field.increment) {
line += ' IDENTITY(1, 1)';
}
if (field.dbdefault) {
if (field.type.type_name.match(/boolean/gi)) {
// SQL Server does not have type BOOLEAN so we change it to BIT
if (field.dbdefault.value.match(/true/gi)) {
line += ' DEFAULT 1';
} else {
line += ' DEFAULT 0';
}
} else if (field.dbdefault.type === 'expression') {
line += " DEFAULT (".concat(field.dbdefault.value, ")");
} else if (field.dbdefault.type === 'string') {
line += " DEFAULT '".concat(field.dbdefault.value, "'");
} else {
line += " DEFAULT (".concat(field.dbdefault.value, ")");
}
line = line.replace(/now/gi, 'GETDATE');
}
return line;
});
return lines;
}
}, {
key: "getPrimaryCompositeKey",
value: function getPrimaryCompositeKey(table) {
var primaryCompositeKey = table.indexes ? table.indexes.filter(function (index) {
return index.pk;
}) : [];
var lines = primaryCompositeKey.map(function (key) {
var line = 'PRIMARY KEY';
var columnArr = [];
key.columns.forEach(function (column) {
var columnStr = '';
if (column.type === 'expression') {
columnStr = "(".concat(column.value, ")");
} else {
columnStr = "[".concat(column.value, "]");
}
columnArr.push(columnStr);
});
line += " (".concat(columnArr.join(', '), ")");
return line;
});
return lines;
}
}]);
return SqlServerExporter;
}(_Exporter2["default"]);
}();
var _default = SqlServerExporter;
exports["default"] = _default;

@@ -10,3 +10,3 @@ "use strict";

var _SchemaExporter = _interopRequireDefault(require("../export/SchemaExporter"));
var _ModelExporter = _interopRequireDefault(require("../export/ModelExporter"));

@@ -16,6 +16,6 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function _import(str, format) {
var parser = new _Parser["default"]();
var schema = parser.parse(str, format);
var schemaExporter = new _SchemaExporter["default"](schema);
var dbml = schemaExporter["export"]('dbml');
var database = _Parser["default"].parse(str, format);
var dbml = _ModelExporter["default"]["export"](database.normalize(), 'dbml');
return dbml;

@@ -22,0 +22,0 @@ }

@@ -6,6 +6,6 @@ "use strict";

});
Object.defineProperty(exports, "SchemaExporter", {
Object.defineProperty(exports, "ModelExporter", {
enumerable: true,
get: function get() {
return _SchemaExporter["default"];
return _ModelExporter["default"];
}

@@ -32,3 +32,3 @@ });

var _SchemaExporter = _interopRequireDefault(require("./export/SchemaExporter"));
var _ModelExporter = _interopRequireDefault(require("./export/ModelExporter"));

@@ -35,0 +35,0 @@ var _Parser = _interopRequireDefault(require("./parse/Parser"));

@@ -6,4 +6,12 @@ "use strict";

});
exports.DEFAULT_SCHEMA_NAME = void 0;
exports.TABLE_GROUP = exports.REF = exports.ENUM = exports.TABLE = exports.DEFAULT_SCHEMA_NAME = void 0;
var DEFAULT_SCHEMA_NAME = 'public';
exports.DEFAULT_SCHEMA_NAME = DEFAULT_SCHEMA_NAME;
exports.DEFAULT_SCHEMA_NAME = DEFAULT_SCHEMA_NAME;
var TABLE = 'table';
exports.TABLE = TABLE;
var ENUM = 'enum';
exports.ENUM = ENUM;
var REF = 'ref';
exports.REF = REF;
var TABLE_GROUP = 'table_group';
exports.TABLE_GROUP = TABLE_GROUP;

@@ -14,3 +14,3 @@ "use strict";

var _enum2 = _interopRequireDefault(require("./enum"));
var _enum = _interopRequireDefault(require("./enum"));

@@ -25,2 +25,4 @@ var _tableGroup = _interopRequireDefault(require("./tableGroup"));

var _dbState = _interopRequireDefault(require("./dbState"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

@@ -69,22 +71,28 @@

_ref$tableGroups = _ref.tableGroups,
tableGroups = _ref$tableGroups === void 0 ? [] : _ref$tableGroups;
tableGroups = _ref$tableGroups === void 0 ? [] : _ref$tableGroups,
_ref$project = _ref.project,
project = _ref$project === void 0 ? {} : _ref$project;
_classCallCheck(this, Database);
_element["default"].resetIdCounter();
_this = _possibleConstructorReturn(this, _getPrototypeOf(Database).call(this));
_this.dbState = new _dbState["default"]();
_this = _possibleConstructorReturn(this, _getPrototypeOf(Database).call(this));
_this.generateId();
_this.hasDefaultSchema = false;
_this.schemas = [];
_this.refs = []; // The process order is important. Do not change !
_this.note = project.note;
_this.databaseType = project.database_type;
_this.name = project.name; // The process order is important. Do not change !
_this.processSchemas(schemas);
_this.processTables(tables);
_this.processSchemaElements(tables, _config.TABLE);
_this.processRefs(refs);
_this.processSchemaElements(refs, _config.REF);
_this.processEnums(enums);
_this.processSchemaElements(enums, _config.ENUM);
_this.processTableGroups(tableGroups);
_this.processSchemaElements(tableGroups, _config.TABLE_GROUP);

@@ -95,2 +103,7 @@ return _this;

_createClass(Database, [{
key: "generateId",
value: function generateId() {
this.id = this.dbState.generateId('dbId');
}
}, {
key: "processSchemas",

@@ -122,29 +135,54 @@ value: function processSchemas(rawSchemas) {

}, {
key: "processTables",
value: function processTables(rawTables) {
key: "processSchemaElements",
value: function processSchemaElements(elements, elementType) {
var _this3 = this;
var schema;
rawTables.forEach(function (table) {
if (table.schemaName) {
schema = _this3.findSchema(table.schemaName);
elements.forEach(function (element) {
if (element.schemaName) {
schema = _this3.findOrCreateSchema(element.schemaName);
if (table.schemaName === _config.DEFAULT_SCHEMA_NAME) {
if (element.schemaName === _config.DEFAULT_SCHEMA_NAME) {
_this3.hasDefaultSchema = true;
}
} else {
schema = _this3.findSchema(_config.DEFAULT_SCHEMA_NAME);
schema = _this3.findOrCreateSchema(_config.DEFAULT_SCHEMA_NAME);
}
schema.pushTable(new _table["default"](_objectSpread({}, table, {
schema: schema
})));
switch (elementType) {
case _config.TABLE:
schema.pushTable(new _table["default"](_objectSpread({}, element, {
schema: schema
})));
break;
case _config.ENUM:
schema.pushEnum(new _enum["default"](_objectSpread({}, element, {
schema: schema
})));
break;
case _config.TABLE_GROUP:
schema.pushTableGroup(new _tableGroup["default"](_objectSpread({}, element, {
schema: schema
})));
break;
case _config.REF:
schema.pushRef(new _ref2["default"](_objectSpread({}, element, {
schema: schema
})));
break;
default:
break;
}
});
}
}, {
key: "findSchema",
value: function findSchema(schemaName) {
key: "findOrCreateSchema",
value: function findOrCreateSchema(schemaName) {
var schema = this.schemas.find(function (s) {
return s.name === schemaName || s.alias === schemaName;
});
}); // create new schema if schema not found

@@ -163,75 +201,5 @@ if (!schema) {

}, {
key: "processRefs",
value: function processRefs(rawRefs) {
var _this4 = this;
rawRefs.forEach(function (ref) {
_this4.pushRef(new _ref2["default"](_objectSpread({}, ref, {
database: _this4
})));
});
}
}, {
key: "pushRef",
value: function pushRef(ref) {
this.checkRef(ref);
this.refs.push(ref);
}
}, {
key: "checkRef",
value: function checkRef(ref) {
if (this.refs.some(function (r) {
return r.equals(ref);
})) {
ref.error('Reference with same endpoints duplicated');
}
}
}, {
key: "processEnums",
value: function processEnums(rawEnums) {
var _this5 = this;
var schema;
rawEnums.forEach(function (_enum) {
if (_enum.schemaName) {
schema = _this5.findSchema(_enum.schemaName);
if (_enum.schemaName === _config.DEFAULT_SCHEMA_NAME) {
_this5.hasDefaultSchema = true;
}
} else {
schema = _this5.findSchema(_config.DEFAULT_SCHEMA_NAME);
}
schema.pushEnum(new _enum2["default"](_objectSpread({}, _enum, {
schema: schema
})));
});
}
}, {
key: "processTableGroups",
value: function processTableGroups(rawTableGroups) {
var _this6 = this;
var schema;
rawTableGroups.forEach(function (tableGroup) {
if (tableGroup.schemaName) {
schema = _this6.findSchema(tableGroup.schemaName);
if (tableGroup.schemaName === _config.DEFAULT_SCHEMA_NAME) {
_this6.hasDefaultSchema = true;
}
} else {
schema = _this6.findSchema(_config.DEFAULT_SCHEMA_NAME);
}
schema.pushTableGroup(new _tableGroup["default"](_objectSpread({}, tableGroup, {
schema: schema
})));
});
}
}, {
key: "findTable",
value: function findTable(rawTable) {
var schema = this.findSchema(rawTable.schemaName || _config.DEFAULT_SCHEMA_NAME);
var schema = this.findOrCreateSchema(rawTable.schemaName || _config.DEFAULT_SCHEMA_NAME);

@@ -253,3 +221,6 @@ if (!schema) {

return {
hasDefaultSchema: this.hasDefaultSchema
hasDefaultSchema: this.hasDefaultSchema,
note: this.note,
databaseType: this.databaseType,
name: this.name
};

@@ -263,5 +234,2 @@ }

return s["export"]();
}),
refs: this.refs.map(function (r) {
return r["export"]();
})

@@ -276,5 +244,2 @@ };

return s.id;
}),
refIds: this.refs.map(function (r) {
return r.id;
})

@@ -304,5 +269,2 @@ };

});
this.refs.forEach(function (ref) {
return ref.normalize(normalizedModel);
});
return normalizedModel;

@@ -309,0 +271,0 @@ }

@@ -67,12 +67,5 @@ "use strict";

this.token = token;
this.generateId();
}
_createClass(Element, [{
key: "generateId",
value: function generateId() {
this.id = Element.idCounter;
Element.incIdCounter();
}
}, {
key: "bind",

@@ -87,12 +80,2 @@ value: function bind(selection) {

}
}], [{
key: "incIdCounter",
value: function incIdCounter() {
Element.idCounter += 1;
}
}, {
key: "resetIdCounter",
value: function resetIdCounter() {
Element.idCounter = 1;
}
}]);

@@ -103,3 +86,2 @@

Element.idCounter = 1;
var _default = Element;

@@ -106,0 +88,0 @@ /* eslint-enable */

@@ -12,2 +12,4 @@ "use strict";

var _utils = require("./utils");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

@@ -61,10 +63,19 @@

_this.fieldName = fieldName;
_this.ref = ref; // Use name of schema,table and field object
_this.ref = ref;
_this.dbState = _this.ref.dbState;
_this.generateId(); // Use name of schema,table and field object
// Name in constructor could be alias
var schema = ref.database.findSchema(schemaName || _config.DEFAULT_SCHEMA_NAME);
var schema = ref.schema.database.findOrCreateSchema(schemaName || _config.DEFAULT_SCHEMA_NAME);
var table = schema.findTable(tableName);
if (!table) {
_this.error("Can't find table ".concat((0, _utils.shouldPrintSchema)(schema) ? "\"".concat(schema.name, "\".") : '', "\"").concat(tableName, "\""));
}
var field = table.findField(fieldName);
_this.setField(field);
_this.setField(field, table);

@@ -75,5 +86,10 @@ return _this;

_createClass(Endpoint, [{
key: "generateId",
value: function generateId() {
this.id = this.dbState.generateId('endpointId');
}
}, {
key: "equals",
value: function equals(endpoint) {
return this.field.id === endpoint.id;
return this.field.id === endpoint.field.id;
}

@@ -105,8 +121,9 @@ }, {

key: "setField",
value: function setField(field) {
value: function setField(field, table) {
if (!field) {
this.error("Can't find field ".concat(this.fieldName, " in table ").concat(this.tableName));
this.error("Can't find field ".concat((0, _utils.shouldPrintSchema)(table.schema) ? "\"".concat(table.schema.name, "\".") : '', "\"").concat(this.fieldName, "\" in table \"").concat(this.tableName, "\""));
}
this.field = field;
field.pushEndpoint(this);
}

@@ -113,0 +130,0 @@ }, {

@@ -12,2 +12,4 @@ "use strict";

var _utils = require("./utils");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

@@ -67,3 +69,6 @@

_this.schema = schema;
_this.dbState = _this.schema.dbState;
_this.generateId();
_this.processValues(values);

@@ -75,2 +80,7 @@

_createClass(Enum, [{
key: "generateId",
value: function generateId() {
this.id = this.dbState.generateId('enumId');
}
}, {
key: "processValues",

@@ -98,3 +108,3 @@ value: function processValues(rawValues) {

})) {
value.error("Enum value ".concat(value.name, " existed in enum ").concat(this.name));
value.error("Enum value \"".concat(value.name, "\" existed in enum ").concat((0, _utils.shouldPrintSchema)(this.schema) ? "\"".concat(this.schema.name, "\".") : '', "\"").concat(this.name, "\""));
}

@@ -114,3 +124,3 @@ }

})) {
this.error("Field ".concat(field.table.schema.name, ".").concat(field.table.name, ".").concat(field.name, " already associated with enum ").concat(this.schema.name, ".").concat(this.name));
this.error("Field ".concat((0, _utils.shouldPrintSchema)(field.table.schema) ? "\"".concat(field.table.schema.name, "\".") : '', "\"").concat(field.table.name, "\".\"").concat(field.name, "\" already associated with enum ").concat((0, _utils.shouldPrintSchema)(this.schema) ? "\"".concat(this.schema.name, "\".") : '').concat(this.name, "\""));
}

@@ -117,0 +127,0 @@ }

@@ -61,2 +61,6 @@ "use strict";

_this._enum = _enum;
_this.dbState = _this._enum.dbState;
_this.generateId();
return _this;

@@ -66,2 +70,7 @@ }

_createClass(EnumValue, [{
key: "generateId",
value: function generateId() {
this.id = this.dbState.generateId('enumValueId');
}
}, {
key: "export",

@@ -68,0 +77,0 @@ value: function _export() {

@@ -78,4 +78,8 @@ "use strict";

_this.increment = increment;
_this.endpoints = [];
_this.table = table;
_this.endpoints = [];
_this.dbState = _this.table.dbState;
_this.generateId();
return _this;

@@ -85,2 +89,7 @@ }

_createClass(Field, [{
key: "generateId",
value: function generateId() {
this.id = this.dbState.generateId('fieldId');
}
}, {
key: "pushEndpoint",

@@ -104,2 +113,11 @@ value: function pushEndpoint(endpoint) {

}, {
key: "exportChildIds",
value: function exportChildIds() {
return {
endpointIds: this.endpoints.map(function (e) {
return e.id;
})
};
}
}, {
key: "shallowExport",

@@ -123,3 +141,3 @@ value: function shallowExport() {

id: this.id
}, this.shallowExport(), {}, this.exportParentIds())));
}, this.shallowExport(), {}, this.exportChildIds(), {}, this.exportParentIds())));
}

@@ -126,0 +144,0 @@ }]);

@@ -54,2 +54,6 @@ "use strict";

_this.index = index;
_this.dbState = _this.index.dbState;
_this.generateId();
return _this;

@@ -59,2 +63,7 @@ }

_createClass(IndexColumn, [{
key: "generateId",
value: function generateId() {
this.id = this.dbState.generateId('indexColumnId');
}
}, {
key: "export",

@@ -61,0 +70,0 @@ value: function _export() {

@@ -65,3 +65,6 @@ "use strict";

_this.table = table;
_this.dbState = _this.table.dbState;
_this.generateId();
_this.processIndexColumns(columns);

@@ -73,2 +76,7 @@

_createClass(Index, [{
key: "generateId",
value: function generateId() {
this.id = this.dbState.generateId('indexId');
}
}, {
key: "processIndexColumns",

@@ -75,0 +83,0 @@ value: function processIndexColumns(rawColumns) {

@@ -64,4 +64,4 @@ "use strict";

token = _ref.token,
_ref$database = _ref.database,
database = _ref$database === void 0 ? {} : _ref$database;
_ref$schema = _ref.schema,
schema = _ref$schema === void 0 ? {} : _ref$schema;

@@ -74,5 +74,8 @@ _classCallCheck(this, Ref);

_this.onUpdate = onUpdate;
_this.database = database;
_this.endpoints = [];
_this.schema = schema;
_this.dbState = _this.schema.dbState;
_this.generateId();
_this.processEndpoints(endpoints);

@@ -84,2 +87,7 @@

_createClass(Ref, [{
key: "generateId",
value: function generateId() {
this.id = this.dbState.generateId('refId');
}
}, {
key: "processEndpoints",

@@ -144,3 +152,3 @@ value: function processEndpoints(rawEndpoints) {

return {
databaseId: this.database.id
schemaId: this.schema.id
};

@@ -147,0 +155,0 @@ }

@@ -16,4 +16,8 @@ "use strict";

var _utils = require("./utils");
var _tableGroup = _interopRequireDefault(require("./tableGroup"));
var _ref2 = _interopRequireDefault(require("./ref"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

@@ -59,2 +63,4 @@

tables = _ref$tables === void 0 ? [] : _ref$tables,
_ref$refs = _ref.refs,
refs = _ref$refs === void 0 ? [] : _ref$refs,
_ref$enums = _ref.enums,

@@ -74,2 +80,3 @@ enums = _ref$enums === void 0 ? [] : _ref$enums,

_this.tableGroups = [];
_this.refs = [];
_this.name = name;

@@ -79,3 +86,6 @@ _this.note = note;

_this.database = database;
_this.dbState = _this.database.dbState;
_this.generateId();
_this.processTables(tables);

@@ -85,2 +95,4 @@

_this.processRefs(refs);
_this.processTableGroups(tableGroups);

@@ -92,2 +104,7 @@

_createClass(Schema, [{
key: "generateId",
value: function generateId() {
this.id = this.dbState.generateId('schemaId');
}
}, {
key: "processTables",

@@ -115,3 +132,3 @@ value: function processTables(rawTables) {

})) {
table.error("Table ".concat(table.name, " existed"));
table.error("Table ".concat((0, _utils.shouldPrintSchema)(this) ? "\"".concat(this.name, "\".") : '', "\"").concat(table.name, "\" existed"));
}

@@ -150,3 +167,3 @@ }

})) {
_enum.error("Enum ".concat(this.name, ".").concat(_enum.name, " existed"));
_enum.error("Enum ".concat((0, _utils.shouldPrintSchema)(this) ? "\"".concat(this.name, "\".") : '', "\"").concat(_enum.name, "\" existed"));
}

@@ -170,9 +187,35 @@ }

}, {
key: "processRefs",
value: function processRefs(rawRefs) {
var _this4 = this;
rawRefs.forEach(function (ref) {
_this4.pushRef(new _ref2["default"](_objectSpread({}, ref, {
schema: _this4
})));
});
}
}, {
key: "pushRef",
value: function pushRef(ref) {
this.checkRef(ref);
this.refs.push(ref);
}
}, {
key: "checkRef",
value: function checkRef(ref) {
if (this.refs.some(function (r) {
return r.equals(ref);
})) {
ref.error('Reference with same endpoints duplicated');
}
}
}, {
key: "processTableGroups",
value: function processTableGroups(rawTableGroups) {
var _this4 = this;
var _this5 = this;
rawTableGroups.forEach(function (tableGroup) {
_this4.pushTableGroup(new _tableGroup["default"](_objectSpread({}, tableGroup, {
schema: _this4
_this5.pushTableGroup(new _tableGroup["default"](_objectSpread({}, tableGroup, {
schema: _this5
})));

@@ -193,3 +236,3 @@ });

})) {
tableGroup.error("Table Group named ".concat(tableGroup.name, " existed"));
tableGroup.error("Table Group ".concat((0, _utils.shouldPrintSchema)(this) ? "\"".concat(this.name, "\".") : '', "\"").concat(tableGroup.name, "\" existed"));
}

@@ -219,2 +262,5 @@ }

return tg["export"]();
}),
refs: this.refs.map(function (r) {
return r["export"]();
})

@@ -235,2 +281,5 @@ };

return tg.id;
}),
refIds: this.refs.map(function (r) {
return r.id;
})

@@ -270,2 +319,5 @@ };

});
this.refs.forEach(function (ref) {
return ref.normalize(model);
});
}

@@ -272,0 +324,0 @@ }]);

@@ -16,2 +16,4 @@ "use strict";

var _utils = require("./utils");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

@@ -74,3 +76,6 @@

_this.schema = schema;
_this.dbState = _this.schema.dbState;
_this.generateId();
_this.processFields(fields);

@@ -84,2 +89,7 @@

_createClass(Table, [{
key: "generateId",
value: function generateId() {
this.id = this.dbState.generateId('tableId');
}
}, {
key: "processFields",

@@ -111,3 +121,3 @@ value: function processFields(rawFields) {

})) {
field.error("Field ".concat(field.name, " existed in table ").concat(this.name));
field.error("Field \"".concat(field.name, "\" existed in table ").concat((0, _utils.shouldPrintSchema)(this.schema) ? "\"".concat(this.schema.name, "\".") : '', "\"").concat(this.name, "\""));
}

@@ -139,3 +149,3 @@ }

if (column.type === 'column' && !_this4.findField(column.value)) {
index.error("Column ".concat(column.value, " do not exist in table ").concat(_this4.name));
index.error("Column \"".concat(column.value, "\" do not exist in table ").concat((0, _utils.shouldPrintSchema)(_this4.schema) ? "\"".concat(_this4.schema.name, "\".") : '', "\"").concat(_this4.name, "\""));
}

@@ -199,3 +209,4 @@ });

alias: this.alias,
note: this.note
note: this.note,
headerColor: this.headerColor
};

@@ -202,0 +213,0 @@ }

@@ -10,2 +10,4 @@ "use strict";

var _utils = require("./utils");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

@@ -58,3 +60,6 @@

_this.schema = schema;
_this.dbState = _this.schema.dbState;
_this.generateId();
_this.processTables(tables);

@@ -66,2 +71,7 @@

_createClass(TableGroup, [{
key: "generateId",
value: function generateId() {
this.id = this.dbState.generateId('tableGroupId');
}
}, {
key: "processTables",

@@ -75,3 +85,3 @@ value: function processTables(rawTables) {

if (!table) {
_this2.error("Table ".concat(rawTable.schemaName ? "".concat(rawTable.schemaName, ".") : '').concat(rawTable.name, " don't exist"));
_this2.error("Table ".concat(rawTable.schemaName ? "\"".concat(rawTable.schemaName, "\".") : '').concat(rawTable.name, " don't exist"));
}

@@ -95,7 +105,7 @@

})) {
this.error("Table ".concat(table.schema.name, ".").concat(table.name, " is already in the group"));
this.error("Table ".concat((0, _utils.shouldPrintSchema)(table.schema) ? "\"".concat(table.schema.name, "\".") : '', ".").concat(table.name, " is already in the group"));
}
if (table.group) {
this.error("Table ".concat(table.schema.name, ".").concat(table.name, " is already in group ").concat(table.group.name));
this.error("Table ".concat((0, _utils.shouldPrintSchema)(table.schema) ? "\"".concat(table.schema.name, "\".") : '', ".").concat(table.name, " is already in group ").concat((0, _utils.shouldPrintSchema)(table.group.schema) ? "\"".concat(table.group.schema.name, "\".") : '').concat(table.group.name));
}

@@ -102,0 +112,0 @@ }

@@ -8,3 +8,3 @@ "use strict";

var _schema = _interopRequireDefault(require("../schema/schema"));
var _database = _interopRequireDefault(require("../model_structure/database"));

@@ -34,13 +34,14 @@ var _mysqlParser = _interopRequireDefault(require("./mysqlParser"));

_classCallCheck(this, Parser);
this.mysqlParser = _mysqlParser["default"];
this.postgresParser = _postgresParser["default"];
this.dbmlParser = _dbmlParser["default"];
this.schemarbParser = _schemarbParser["default"];
}
_createClass(Parser, [{
_createClass(Parser, null, [{
key: "parseJSONToDatabase",
value: function parseJSONToDatabase(rawDatabase) {
var database = new _database["default"](rawDatabase);
return database;
}
}, {
key: "parseMySQLToJSON",
value: function parseMySQLToJSON(str) {
return this.mysqlParser.parse(str);
return _mysqlParser["default"].parse(str);
}

@@ -50,3 +51,3 @@ }, {

value: function parsePostgresToJSON(str) {
return this.postgresParser.parse(str);
return _postgresParser["default"].parse(str);
}

@@ -56,3 +57,3 @@ }, {

value: function parseDBMLToJSON(str) {
return this.dbmlParser.parse(str);
return _dbmlParser["default"].parse(str);
}

@@ -62,3 +63,3 @@ }, {

value: function parseSchemaRbToJSON(str) {
return this.schemarbParser.parse(str);
return _schemarbParser["default"].parse(str);
}

@@ -68,19 +69,19 @@ }, {

value: function parse(str, format) {
var rawSchema = {};
var rawDatabase = {};
switch (format) {
case 'mysql':
rawSchema = this.parseMySQLToJSON(str);
rawDatabase = Parser.parseMySQLToJSON(str);
break;
case 'postgres':
rawSchema = this.parsePostgresToJSON(str);
rawDatabase = Parser.parsePostgresToJSON(str);
break;
case 'dbml':
rawSchema = this.parseDBMLToJSON(str);
rawDatabase = Parser.parseDBMLToJSON(str);
break;
case 'schemarb':
rawSchema = this.parseSchemaRbToJSON(str);
rawDatabase = Parser.parseSchemaRbToJSON(str);
break;

@@ -90,5 +91,5 @@

if (_typeof(str) === 'object') {
rawSchema = str;
rawDatabase = str;
} else {
rawSchema = JSON.parse(str);
rawDatabase = JSON.parse(str);
}

@@ -102,11 +103,5 @@

var schema = Parser.parseJSONToSchema(rawSchema);
var schema = Parser.parseJSONToDatabase(rawDatabase);
return schema;
}
}], [{
key: "parseJSONToSchema",
value: function parseJSONToSchema(rawSchema) {
var schema = new _schema["default"](rawSchema);
return schema;
}
}]);

@@ -113,0 +108,0 @@

{
"name": "@dbml/core",
"version": "1.3.1",
"version": "2.0.0-alpha.0",
"description": "> TODO: description",
"author": "Holistics <dev@holistics.io>",
"license": "Apache-2.0",
"homepage": "https://dbml-lang.org/home/",
"homepage": "https://dbml.org",
"repository": "https://github.com/holistics/dbml/tree/master/packages/dbml-core",

@@ -56,3 +56,3 @@ "keywords": [

},
"gitHead": "707a4cae94b229045e8bef261ad8c7de8f0e0a65"
"gitHead": "a437c3c38a201d958f1d78ceb34cfb3e85248e7e"
}

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc