datasquirel/package-shared/utils/db/schema/resolve-schema-foreign-keys.ts
Benjamin Toby 7e8bb37c09 Updates
2025-07-05 14:59:30 +01:00

39 lines
1.2 KiB
TypeScript

import { DSQL_DatabaseSchemaType } from "../../../types";
import _ from "lodash";
type Params = {
dbSchema: DSQL_DatabaseSchemaType;
userId: string | number;
};
export default function resolveSchemaForeignKeys({ dbSchema, userId }: Params) {
let newDbSchema = _.cloneDeep(dbSchema);
for (let t = 0; t < newDbSchema.tables.length; t++) {
const tableSchema = newDbSchema.tables[t];
for (let f = 0; f < tableSchema.fields.length; f++) {
const fieldSchema = tableSchema.fields[f];
if (fieldSchema.foreignKey?.destinationTableColumnName) {
const fkDestinationTableIndex = newDbSchema.tables.findIndex(
(tbl) =>
tbl.tableName ==
fieldSchema.foreignKey?.destinationTableName
);
/**
* Delete current Foreign Key if related table doesn't exist
* or has been deleted
*/
if (fkDestinationTableIndex < 0) {
delete newDbSchema.tables[t].fields[f].foreignKey;
continue;
}
}
}
}
return newDbSchema;
}