Merge pull request #3769 from strapi/chore/unique-indexes

Support unique indexes with clean error messages
This commit is contained in:
Alexandre BODIN 2019-08-12 11:43:26 +02:00 committed by GitHub
commit c20c0c444e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 42 additions and 3 deletions

View File

@ -8,6 +8,7 @@
"type": {
"type": "string",
"required": true,
"unique": true,
"configurable": true
}
}

View File

@ -222,8 +222,15 @@ module.exports = async ({
await ORM.knex.transaction(trx => rebuildTable(trx));
await generateIndexes(table);
} catch (err) {
strapi.log.error('Migration failed');
strapi.log.error(err);
if (err.message.includes('UNIQUE constraint failed')) {
strapi.log.error(
`Unique constraint fails, make sure to update your data and restart to apply the unique constraint.\n\t- ${err.stack}`
);
} else {
strapi.log.error(`Migration failed`);
strapi.log.error(err);
}
return false;
}
} else {
@ -250,7 +257,24 @@ module.exports = async ({
});
};
await ORM.knex.transaction(trx => alterTable(trx));
try {
await ORM.knex.transaction(trx => alterTable(trx));
} catch (err) {
if (err.code === '23505' && definition.client === 'pg') {
strapi.log.error(
`Unique constraint fails, make sure to update your data and restart to apply the unique constraint.\n\t- ${err.message}\n\t- ${err.detail}`
);
} else if (definition.client === 'mysql' && err.errno === 1062) {
strapi.log.error(
`Unique constraint fails, make sure to update your data and restart to apply the unique constraint.\n\t- ${err.sqlMessage}`
);
} else {
strapi.log.error(`Migration failed`);
strapi.log.error(err);
}
return false;
}
}
await storeTable(table, attributes);

View File

@ -272,6 +272,20 @@ module.exports = ({ models, target, plugin = false }, ctx) => {
definition.collectionName
);
Model.on('index', error => {
if (error) {
if (error.code === 11000) {
strapi.log.error(
`Unique constraint fails, make sure to update your data and restart to apply the unique constraint.\n\t- ${error.message}`
);
} else {
strapi.log.error(
`An index error happened, it wasn't applied.\n\t- ${error.message}`
);
}
}
});
if (!plugin) {
global[definition.globalName] = Model;
}