bun-mariadb/dist/lib/schema/resolve-table.js

35 lines
1.4 KiB
JavaScript

import _ from "lodash";
export default function resolveTable(table, db_schema) {
if (!table.parentTableName) {
return _.cloneDeep(table);
}
const parentTable = db_schema.tables.find((schemaTable) => schemaTable.tableName === table.parentTableName);
if (!parentTable) {
throw new Error(`Parent table \`${table.parentTableName}\` not found for \`${table.tableName}\``);
}
const mergedFieldsMap = new Map();
(parentTable.fields || []).forEach((f) => {
if (f.fieldName)
mergedFieldsMap.set(f.fieldName, _.cloneDeep(f));
});
(table.fields || []).forEach((f) => {
if (f.fieldName) {
const existing = mergedFieldsMap.get(f.fieldName) || {};
mergedFieldsMap.set(f.fieldName, _.merge({}, existing, f));
}
});
return {
..._.cloneDeep(parentTable),
tableName: table.tableName,
tableDescription: table.tableDescription || parentTable.tableDescription,
collation: table.collation || parentTable.collation,
isVector: table.isVector !== undefined ? table.isVector : parentTable.isVector,
fields: Array.from(mergedFieldsMap.values()),
indexes: _.uniqBy([...(parentTable.indexes || []), ...(table.indexes || [])], "indexName"),
uniqueConstraints: [
...(parentTable.uniqueConstraints || []),
...(table.uniqueConstraints || []),
],
};
}