Enhance foreign key management in sequelize.js by refining schema handling and improving logging for foreign key removal during model synchronization. Add detailed console outputs for better visibility on foreign key operations and error handling.
This commit is contained in:
@@ -493,7 +493,10 @@ const syncModelsAlways = async (models) => {
|
|||||||
// Entferne bestehende Foreign Keys vor dem Sync, damit Sequelize sie nicht aktualisiert
|
// Entferne bestehende Foreign Keys vor dem Sync, damit Sequelize sie nicht aktualisiert
|
||||||
try {
|
try {
|
||||||
const tableName = model.tableName;
|
const tableName = model.tableName;
|
||||||
const schema = model.schema || model.options?.schema || 'public';
|
// Schema kann eine Funktion sein, daher prüfen wir model.options.schema direkt
|
||||||
|
const schema = model.options?.schema || 'public';
|
||||||
|
|
||||||
|
console.log(` 🔍 Checking for foreign keys in ${schema}.${tableName}...`);
|
||||||
const foreignKeys = await sequelize.query(`
|
const foreignKeys = await sequelize.query(`
|
||||||
SELECT tc.constraint_name
|
SELECT tc.constraint_name
|
||||||
FROM information_schema.table_constraints AS tc
|
FROM information_schema.table_constraints AS tc
|
||||||
@@ -506,16 +509,22 @@ const syncModelsAlways = async (models) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (foreignKeys && foreignKeys.length > 0) {
|
if (foreignKeys && foreignKeys.length > 0) {
|
||||||
console.log(` ⚠️ Removing ${foreignKeys.length} existing foreign keys from ${model.name} before sync`);
|
console.log(` ⚠️ Found ${foreignKeys.length} existing foreign keys:`, foreignKeys.map(fk => fk.constraint_name).join(', '));
|
||||||
|
console.log(` ⚠️ Removing ${foreignKeys.length} existing foreign keys from ${model.name} (schema: ${schema}) before sync`);
|
||||||
for (const fk of foreignKeys) {
|
for (const fk of foreignKeys) {
|
||||||
|
console.log(` 🗑️ Dropping constraint: ${fk.constraint_name}`);
|
||||||
await sequelize.query(`
|
await sequelize.query(`
|
||||||
ALTER TABLE "${schema}"."${tableName}"
|
ALTER TABLE "${schema}"."${tableName}"
|
||||||
DROP CONSTRAINT IF EXISTS "${fk.constraint_name}"
|
DROP CONSTRAINT IF EXISTS "${fk.constraint_name}" CASCADE
|
||||||
`);
|
`);
|
||||||
}
|
}
|
||||||
|
console.log(` ✅ All foreign keys removed for ${model.name}`);
|
||||||
|
} else {
|
||||||
|
console.log(` ✅ No foreign keys found for ${model.name}`);
|
||||||
}
|
}
|
||||||
} catch (fkError) {
|
} catch (fkError) {
|
||||||
console.warn(` ⚠️ Could not remove foreign keys for ${model.name}:`, fkError.message);
|
console.warn(` ⚠️ Could not remove foreign keys for ${model.name}:`, fkError.message);
|
||||||
|
console.warn(` ⚠️ Error details:`, fkError);
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log(` 🔄 Syncing model ${model.name} with constraints: false`);
|
console.log(` 🔄 Syncing model ${model.name} with constraints: false`);
|
||||||
|
|||||||
Reference in New Issue
Block a user