prisma-dbml-generator
Version:
Prisma DBML Generator
67 lines (66 loc) • 3 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateManyToManyTables = void 0;
const model_1 = require("./model");
function generateManyToManyTables(models, mapToDbSchema = false) {
const manyToManyFields = filterManyToManyRelationFields(models);
if (manyToManyFields.length === 0) {
return [];
}
return generateTables(manyToManyFields, models, [], mapToDbSchema);
}
exports.generateManyToManyTables = generateManyToManyTables;
function generateTables(manyToManyFields, models, manyToManyTables = [], mapToDbSchema = false) {
const manyFirst = manyToManyFields.shift();
if (!manyFirst) {
return manyToManyTables;
}
// In the case of a manyMany, second field should be found
const manySecond = manyToManyFields.find((field) => field.relationName === manyFirst.relationName);
// If its a manyMany, generate the join table
// Else, it's a oneMany: ignore it and continue
if (manySecond) {
manyToManyTables.push(`Table ${manyFirst === null || manyFirst === void 0 ? void 0 : manyFirst.relationName} {\n` +
`${generateJoinFields([manyFirst, manySecond], models, mapToDbSchema)}` +
'\n}');
}
return generateTables(manyToManyFields.filter((field) => field.relationName !== manyFirst.relationName), models, manyToManyTables, mapToDbSchema);
}
function generateJoinFields(fields, models, mapToDbSchema = false) {
return fields
.map((field) => joinField(field, models, mapToDbSchema))
.join('\n');
}
function joinField(field, models, mapToDbSchema = false) {
var _a;
const fieldName = mapToDbSchema
? ((_a = (0, model_1.getModelByType)(models, field.type)) === null || _a === void 0 ? void 0 : _a.dbName) || field.type
: field.type;
return ` ${field.name.toLowerCase()}Id ${getJoinIdType(field, models)} [ref: > ${fieldName}.${field.relationToFields[0]}]`;
}
function getJoinIdType(joinField, models) {
const joinIdField = models
.filter((model) => model.name === joinField.type)
.map((model) => model.fields.find((field) => field.name === joinField.relationToFields[0]))[0];
return joinIdField.type;
}
function filterManyToManyRelationFields(models) {
return models
.map((model) => model.fields
.filter((field) => {
var _a, _b;
return field.relationName &&
field.isList &&
((_a = field.relationFromFields) === null || _a === void 0 ? void 0 : _a.length) === 0 &&
// Updated this condition to match manyMany fields as defined in the new DMMF
((_b = field.relationToFields) === null || _b === void 0 ? void 0 : _b.length) === 0;
})
// As the relationToFields is not populated in the DMMF, we need to populate it manually
.map((field) => ({
...field,
relationToFields: model.fields
.filter((f) => f.isId)
.map((f) => f.name),
})))
.flat();
}
;