import { DSQL_FieldSchemaType, DSQL_ForeignKeyType, DSQL_MYSQL_FOREIGN_KEYS_Type, } from "../../types"; import dbHandler from "../../functions/backend/dbHandler"; type Param = { dbFullName: string; tableName: string; fields: DSQL_FieldSchemaType[]; clone?: boolean; }; /** * Handle MYSQL Foreign Keys * =================================================== * @description Iterate through each datasquirel schema * table index(if available), and perform operations */ export default async function handleTableForeignKey({ dbFullName, tableName, fields, clone, }: Param) { let addFkSQL = `ALTER TABLE \`${dbFullName}\`.\`${tableName}\``; for (let i = 0; i < fields.length; i++) { const { fieldName, foreignKey } = fields[i]; if (!clone && foreignKey && fieldName) { const { destinationTableName, destinationTableColumnName, cascadeDelete, cascadeUpdate, foreignKeyName, } = foreignKey; addFkSQL += ` ADD CONSTRAINT \`${foreignKeyName}\` FOREIGN KEY (\`${fieldName}\`)`; addFkSQL += ` REFERENCES \`${destinationTableName}\`(\`${destinationTableColumnName}\`)`; if (cascadeDelete) addFkSQL += ` ON DELETE CASCADE`; if (cascadeUpdate) addFkSQL += ` ON UPDATE CASCADE`; addFkSQL += `,`; } } const finalAddFKSQL = addFkSQL.endsWith(",") ? addFkSQL.replace(/\,$/, "") : undefined; if (finalAddFKSQL) { const addForeignKey = (await dbHandler({ query: finalAddFKSQL, })) as any; } }