@dbml/core
Version:
> TODO: description
378 lines (375 loc) • 17.9 kB
JavaScript
function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _lodash = _interopRequireWildcard(require("lodash"));
var _schema = _interopRequireDefault(require("./schema"));
var _ref3 = _interopRequireDefault(require("./ref"));
var _enum2 = _interopRequireDefault(require("./enum"));
var _tableGroup = _interopRequireDefault(require("./tableGroup"));
var _table = _interopRequireDefault(require("./table"));
var _stickyNote = _interopRequireDefault(require("./stickyNote"));
var _element = _interopRequireDefault(require("./element"));
var _config = require("./config");
var _dbState = _interopRequireDefault(require("./dbState"));
var _tablePartial = _interopRequireDefault(require("./tablePartial"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
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 } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } 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 _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
var Database = /*#__PURE__*/function (_Element) {
_inherits(Database, _Element);
var _super = _createSuper(Database);
function Database(_ref) {
var _this;
var _ref$schemas = _ref.schemas,
schemas = _ref$schemas === void 0 ? [] : _ref$schemas,
_ref$tables = _ref.tables,
tables = _ref$tables === void 0 ? [] : _ref$tables,
_ref$notes = _ref.notes,
notes = _ref$notes === void 0 ? [] : _ref$notes,
_ref$enums = _ref.enums,
enums = _ref$enums === void 0 ? [] : _ref$enums,
_ref$refs = _ref.refs,
refs = _ref$refs === void 0 ? [] : _ref$refs,
_ref$tableGroups = _ref.tableGroups,
tableGroups = _ref$tableGroups === void 0 ? [] : _ref$tableGroups,
_ref$project = _ref.project,
project = _ref$project === void 0 ? {} : _ref$project,
_ref$aliases = _ref.aliases,
aliases = _ref$aliases === void 0 ? [] : _ref$aliases,
_ref$records = _ref.records,
records = _ref$records === void 0 ? [] : _ref$records,
_ref$tablePartials = _ref.tablePartials,
tablePartials = _ref$tablePartials === void 0 ? [] : _ref$tablePartials;
_classCallCheck(this, Database);
_this = _super.call(this);
_this.dbState = new _dbState["default"]();
_this.generateId();
_this.hasDefaultSchema = false;
_this.schemas = [];
_this.notes = [];
_this.note = project.note ? (0, _lodash.get)(project, 'note.value', project.note) : null;
_this.noteToken = project.note ? (0, _lodash.get)(project, 'note.token', project.noteToken) : null;
_this.databaseType = project.database_type;
_this.name = project.name;
_this.token = project.token;
_this.aliases = aliases;
_this.records = [];
_this.tablePartials = [];
// The global array containing references with 1 endpoint being a field injected from a partial to a table
// These refs are add to this array when resolving partials in tables (`Table.processPartials()`)
_this.injectedRawRefs = [];
// The process order is important. Do not change !
_this.processNotes(notes);
_this.processRecords(records);
_this.processTablePartials(tablePartials);
_this.processSchemas(schemas);
_this.processSchemaElements(enums, _config.ENUM);
_this.processSchemaElements(tables, _config.TABLE);
_this.processSchemaElements(notes, _config.NOTE);
_this.processSchemaElements(refs, _config.REF);
_this.processSchemaElements(tableGroups, _config.TABLE_GROUP);
_this.injectedRawRefs.forEach(function (rawRef) {
var schema = _this.findOrCreateSchema(_config.DEFAULT_SCHEMA_NAME);
var ref = new _ref3["default"](_objectSpread(_objectSpread({}, rawRef), {}, {
schema: schema
}));
if (schema.refs.some(function (r) {
return r.equals(ref);
})) return;
schema.pushRef(ref);
});
return _this;
}
_createClass(Database, [{
key: "generateId",
value: function generateId() {
this.id = this.dbState.generateId('dbId');
}
}, {
key: "processNotes",
value: function processNotes(rawNotes) {
var _this2 = this;
rawNotes.forEach(function (note) {
_this2.pushNote(new _stickyNote["default"](_objectSpread(_objectSpread({}, note), {}, {
database: _this2
})));
});
}
}, {
key: "processRecords",
value: function processRecords(rawRecords) {
var _this3 = this;
rawRecords.forEach(function (_ref2) {
var schemaName = _ref2.schemaName,
tableName = _ref2.tableName,
columns = _ref2.columns,
values = _ref2.values;
_this3.records.push({
id: _this3.dbState.generateId('recordId'),
schemaName: schemaName,
tableName: tableName,
columns: columns,
values: values
});
});
}
}, {
key: "processTablePartials",
value: function processTablePartials(rawTablePartials) {
var _this4 = this;
rawTablePartials.forEach(function (rawTablePartial) {
_this4.tablePartials.push(new _tablePartial["default"](_objectSpread(_objectSpread({}, rawTablePartial), {}, {
dbState: _this4.dbState
})));
});
}
}, {
key: "pushNote",
value: function pushNote(note) {
this.checkNote(note);
this.notes.push(note);
}
}, {
key: "checkNote",
value: function checkNote(note) {
if (this.notes.some(function (n) {
return n.name === note.name;
})) {
note.error("Notes ".concat(note.name, " existed"));
}
}
}, {
key: "processSchemas",
value: function processSchemas(rawSchemas) {
var _this5 = this;
rawSchemas.forEach(function (schema) {
_this5.pushSchema(new _schema["default"](_objectSpread(_objectSpread({}, schema), {}, {
database: _this5
})));
});
}
}, {
key: "pushSchema",
value: function pushSchema(schema) {
this.checkSchema(schema);
this.schemas.push(schema);
}
}, {
key: "checkSchema",
value: function checkSchema(schema) {
if (this.schemas.some(function (s) {
return s.name === schema.name;
})) {
schema.error("Schemas ".concat(schema.name, " existed"));
}
}
}, {
key: "processSchemaElements",
value: function processSchemaElements(elements, elementType) {
var _this6 = this;
var schema;
elements.forEach(function (element) {
if (element.schemaName) {
schema = _this6.findOrCreateSchema(element.schemaName);
if (element.schemaName === _config.DEFAULT_SCHEMA_NAME) {
// this.hasDefaultSchema = true;
}
} else {
schema = _this6.findOrCreateSchema(_config.DEFAULT_SCHEMA_NAME);
}
switch (elementType) {
case _config.TABLE:
schema.pushTable(new _table["default"](_objectSpread(_objectSpread({}, element), {}, {
schema: schema
})));
break;
case _config.ENUM:
schema.pushEnum(new _enum2["default"](_objectSpread(_objectSpread({}, element), {}, {
schema: schema
})));
break;
case _config.TABLE_GROUP:
schema.pushTableGroup(new _tableGroup["default"](_objectSpread(_objectSpread({}, element), {}, {
schema: schema
})));
break;
case _config.REF:
schema.pushRef(new _ref3["default"](_objectSpread(_objectSpread({}, element), {}, {
schema: schema
})));
break;
default:
break;
}
});
}
}, {
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
if (!schema) {
schema = new _schema["default"]({
name: schemaName,
note: {
value: schemaName === _config.DEFAULT_SCHEMA_NAME ? "Default ".concat(_lodash["default"].capitalize(_config.DEFAULT_SCHEMA_NAME), " Schema") : null
},
database: this
});
this.pushSchema(schema);
}
return schema;
}
}, {
key: "findTableAlias",
value: function findTableAlias(alias) {
var sym = this.aliases.find(function (a) {
return a.name === alias;
});
if (!sym || sym.kind !== 'table') return null;
var schemaName = sym.value.schemaName || _config.DEFAULT_SCHEMA_NAME;
var schema = this.schemas.find(function (s) {
return s.name === schemaName;
});
if (!schema) return null;
var tableName = sym.value.tableName;
var table = schema.tables.find(function (t) {
return t.name === tableName;
});
return table;
}
}, {
key: "findTable",
value: function findTable(schemaName, tableName) {
var table = null;
if (!schemaName) {
table = this.findTableAlias(tableName);
if (table) return table;
}
var schema = this.findOrCreateSchema(schemaName || _config.DEFAULT_SCHEMA_NAME);
if (!schema) {
this.error("Schema ".concat(schemaName || _config.DEFAULT_SCHEMA_NAME, " don't exist"));
}
return schema.findTable(tableName);
}
}, {
key: "findEnum",
value: function findEnum(schemaName, name) {
var schema = this.schemas.find(function (s) {
return s.name === schemaName || s.alias === schemaName;
});
if (!schema) return null;
var _enum = schema.enums.find(function (e) {
return e.name === name;
});
return _enum;
}
}, {
key: "findTablePartial",
value: function findTablePartial(name) {
return this.tablePartials.find(function (tp) {
return tp.name === name;
});
}
}, {
key: "export",
value: function _export() {
return _objectSpread({}, this.exportChild());
}
}, {
key: "shallowExport",
value: function shallowExport() {
return {
hasDefaultSchema: this.hasDefaultSchema,
note: this.note,
databaseType: this.databaseType,
name: this.name
};
}
}, {
key: "exportChild",
value: function exportChild() {
return {
schemas: this.schemas.map(function (s) {
return s["export"]();
}),
notes: this.notes.map(function (n) {
return n["export"]();
}),
records: this.records.map(function (r) {
return _objectSpread({}, r);
})
};
}
}, {
key: "exportChildIds",
value: function exportChildIds() {
return {
schemaIds: this.schemas.map(function (s) {
return s.id;
}),
noteIds: this.notes.map(function (n) {
return n.id;
})
};
}
}, {
key: "normalize",
value: function normalize() {
var normalizedModel = {
database: _defineProperty({}, this.id, _objectSpread(_objectSpread({
id: this.id
}, this.shallowExport()), this.exportChildIds())),
schemas: {},
notes: {},
refs: {},
enums: {},
tableGroups: {},
tables: {},
endpoints: {},
enumValues: {},
indexes: {},
indexColumns: {},
fields: {},
records: {},
tablePartials: {}
};
this.schemas.forEach(function (schema) {
return schema.normalize(normalizedModel);
});
this.notes.forEach(function (note) {
return note.normalize(normalizedModel);
});
this.records.forEach(function (record) {
normalizedModel.records[record.id] = _objectSpread({}, record);
});
this.tablePartials.forEach(function (tablePartial) {
return tablePartial.normalize(normalizedModel);
});
return normalizedModel;
}
}]);
return Database;
}(_element["default"]);
var _default = Database;
exports["default"] = _default;
;