diff --git a/examples/getstarted/plugins/myplugin/models/Test.settings.json b/examples/getstarted/plugins/myplugin/models/Test.settings.json index f2295de4fd..7eb42a2db9 100644 --- a/examples/getstarted/plugins/myplugin/models/Test.settings.json +++ b/examples/getstarted/plugins/myplugin/models/Test.settings.json @@ -8,6 +8,7 @@ "type": { "type": "string", "required": true, + "unique": true, "configurable": true } } diff --git a/packages/strapi-hook-bookshelf/lib/buildDatabaseSchema.js b/packages/strapi-hook-bookshelf/lib/buildDatabaseSchema.js index b8186aaf03..39e900c1ac 100644 --- a/packages/strapi-hook-bookshelf/lib/buildDatabaseSchema.js +++ b/packages/strapi-hook-bookshelf/lib/buildDatabaseSchema.js @@ -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); diff --git a/packages/strapi-hook-mongoose/lib/mount-models.js b/packages/strapi-hook-mongoose/lib/mount-models.js index 4a57c82162..657cf0682d 100644 --- a/packages/strapi-hook-mongoose/lib/mount-models.js +++ b/packages/strapi-hook-mongoose/lib/mount-models.js @@ -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; }