57 lines
1.8 KiB
TypeScript
57 lines
1.8 KiB
TypeScript
import _ from "lodash";
|
|
import type {
|
|
BUN_MARIADB_DatabaseSchemaType,
|
|
BUN_MARIADB_FieldSchemaType,
|
|
BUN_MARIADB_TableSchemaType,
|
|
} from "../../types";
|
|
|
|
export default function resolveTable(
|
|
table: BUN_MARIADB_TableSchemaType,
|
|
db_schema: BUN_MARIADB_DatabaseSchemaType,
|
|
): BUN_MARIADB_TableSchemaType {
|
|
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<string, BUN_MARIADB_FieldSchemaType>();
|
|
|
|
(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 || []),
|
|
],
|
|
};
|
|
}
|