Parse relationships

This commit is contained in:
1ilit 2025-03-01 22:14:16 +04:00
parent f7132596e2
commit d0ea99d294

View File

@ -1,5 +1,6 @@
import { Parser } from "@dbml/core"; import { Parser } from "@dbml/core";
import { arrangeTables } from "../arrangeTables"; import { arrangeTables } from "../arrangeTables";
import { Cardinality, Constraint } from "../../data/constants";
const parser = new Parser(); const parser = new Parser();
@ -52,6 +53,63 @@ export function fromDBML(src) {
tables.push(parsedTable); tables.push(parsedTable);
} }
for (const ref of schema.refs) {
const startTable = ref.endpoints[0].tableName;
const endTable = ref.endpoints[1].tableName;
const startField = ref.endpoints[0].fieldNames[0];
const endField = ref.endpoints[1].fieldNames[0];
const startTableId = tables.findIndex((t) => t.name === startTable);
if (startTableId === -1) continue;
const endTableId = tables.findIndex((t) => t.name === endTable);
if (endTableId === -1) continue;
const endFieldId = tables[endTableId].fields.findIndex(
(f) => f.name === endField,
);
if (endFieldId === -1) continue;
const startFieldId = tables[startTableId].fields.findIndex(
(f) => f.name === startField,
);
if (startFieldId === -1) continue;
const relationship = {};
relationship.name =
"fk_" + startTable + "_" + startField + "_" + endTable;
relationship.startTableId = startTableId;
relationship.endTableId = endTableId;
relationship.endFieldId = endFieldId;
relationship.startFieldId = startFieldId;
relationship.id = relationships.length;
relationship.updateConstraint = ref.onDelete
? ref.onDelete[0].toUpperCase() + ref.onDelete.substring(1)
: Constraint.NONE;
relationship.deleteConstraint = ref.onUpdate
? ref.onUpdate[0].toUpperCase() + ref.onUpdate.substring(1)
: Constraint.NONE;
const startRelation = ref.endpoints[0].relation;
const endRelation = ref.endpoints[1].relation;
if (startRelation === "*" && endRelation === "1") {
relationship.cardinality = Cardinality.MANY_TO_ONE;
}
if (startRelation === "1" && endRelation === "*") {
relationship.cardinality = Cardinality.ONE_TO_MANY;
}
if (startRelation === "1" && endRelation === "1") {
relationship.cardinality = Cardinality.ONE_TO_ONE;
}
relationships.push(relationship);
}
for (const schemaEnum of schema.enums) { for (const schemaEnum of schema.enums) {
const parsedEnum = {}; const parsedEnum = {};