Create a table and add indexes in a single migration with Sequelize
The accepted solution is problematic if the second step fails. Transactions in each step should be used to allow a roll back to ensure all of the migration steps that are inserts or updates are undone if a problem is encountered at any step. For example:
module.exports = {
up: async (queryIntereface) => {
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.createTable('Todos', {
// columns...
}, { transaction });
await queryInterface.addIndex('Todos', ['author_id', 'title'], { transaction }));
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
down: async (queryInterface) {
etc...
Reference
- https://sequelize.org/master/manual/migrations.html#migration-skeleton (search for "transaction()"
Yes, the methods can be chained. In your case you just perform the addIndex
after createTable
method
return queryInterface.createTable('Todos', {
// columns...
}).then(() => queryInterface.addIndex('Todos', ['author_id', 'title']))
.then(() => {
// perform further operations if needed
});