Implement foreign key removal before model synchronization in sequelize.js to prevent conflicts during sync. Add error handling and logging for better visibility on foreign key management.
This commit is contained in:
@@ -490,6 +490,34 @@ const syncModelsAlways = async (models) => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Entferne bestehende Foreign Keys vor dem Sync, damit Sequelize sie nicht aktualisiert
|
||||||
|
try {
|
||||||
|
const tableName = model.tableName;
|
||||||
|
const schema = model.schema || model.options?.schema || 'public';
|
||||||
|
const foreignKeys = await sequelize.query(`
|
||||||
|
SELECT tc.constraint_name
|
||||||
|
FROM information_schema.table_constraints AS tc
|
||||||
|
WHERE tc.constraint_type = 'FOREIGN KEY'
|
||||||
|
AND tc.table_name = :tableName
|
||||||
|
AND tc.table_schema = :schema
|
||||||
|
`, {
|
||||||
|
replacements: { tableName, schema },
|
||||||
|
type: sequelize.QueryTypes.SELECT
|
||||||
|
});
|
||||||
|
|
||||||
|
if (foreignKeys && foreignKeys.length > 0) {
|
||||||
|
console.log(` ⚠️ Removing ${foreignKeys.length} existing foreign keys from ${model.name} before sync`);
|
||||||
|
for (const fk of foreignKeys) {
|
||||||
|
await sequelize.query(`
|
||||||
|
ALTER TABLE "${schema}"."${tableName}"
|
||||||
|
DROP CONSTRAINT IF EXISTS "${fk.constraint_name}"
|
||||||
|
`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (fkError) {
|
||||||
|
console.warn(` ⚠️ Could not remove foreign keys for ${model.name}:`, fkError.message);
|
||||||
|
}
|
||||||
|
|
||||||
console.log(` 🔄 Syncing model ${model.name} with constraints: false`);
|
console.log(` 🔄 Syncing model ${model.name} with constraints: false`);
|
||||||
await model.sync({ alter: true, force: false, constraints: false });
|
await model.sync({ alter: true, force: false, constraints: false });
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user