22

How can I add data to a table in a Sequelize migration script? This is what I got:

module.exports = {
up: function(migration, DataTypes, done) {
    migration.createTable(
        'person',
        {
            name: DataTypes.STRING,
            age: DataTypes.INTEGER
        },
        {
            charset: 'latin1' // default: null
        }
    );
    // I want to insert person and age.
    migration.insert(???);
    done()
},
down: function(migration, DataTypes, done) {
    migration.dropTable('queue');
    done()
}

}

Fossmo
  • 2,862
  • 4
  • 25
  • 47

5 Answers5

19

I figured it out. Sequelize is available from migration.migrator.sequelize. It is possible to do something like this:

up: function (migration, DataTypes, done) {
    migration.createTable(
        'Person',
        {
            name: DataTypes.STRING,
            age: DataTypes.INTEGER,
        }
    ).success(function () {
        migration.migrator.sequelize.query("insert into person (name, age) values ('Donald Duck', 60)");
        done();
    });
},
down: function (migration, DataTypes, done) {
    migration.dropTable(
      'Person'
    ).then(function() {
      done();
    })
}
Alexis N-o
  • 3,954
  • 26
  • 34
Fossmo
  • 2,862
  • 4
  • 25
  • 47
  • 1
    These queries return promises. You'll want to not call `done()` until after the promise is satisfied, otherwise your next migration might fail. `migration.dropTable('Person').then(function(){done()})` – Jeff Fairley Dec 15 '14 at 18:00
  • 1
    `migration.migrator.sequelize.query` should be `migration.sequelize.query` now – Taku Sep 21 '16 at 18:06
12

In the latest version of sequelize this has changed and it should now be

migration.createTable(
    'Person',
    {
        name: DataTypes.STRING,
        age: DataTypes.INTEGER,
    }
).then(function () {
    migration.sequelize.query("insert into person (name, age) values ('Donald Duck', 60)");
    done();
});
Paul Keeble
  • 1,202
  • 2
  • 12
  • 16
11

Actually it is not a good idea to just run a query. queryInterface has create() and bulkCreate() now.

'use strict';
module.exports = {
  up: function(queryInterface, Sequelize) {
    return queryInterface.bulkInsert('roles', [{
      label: 'user',
      createdAt: new Date(),
      updatedAt: new Date()
    }, {
      label: 'admin',
      createdAt: new Date(),
      updatedAt: new Date()
    }]);
  },
  down: function(queryInterface, Sequelize) {
    return queryInterface.bulkDelete('roles', null, {});
  }
};

This returns a promise as expected by sequelize-cli.

Source (adapted): https://github.com/sequelize/sequelize/issues/3210

Diogo Neves
  • 261
  • 2
  • 8
  • 1
    Thanks for this. This answers how to insert data, but what is the right way to get data first? For example, I'm trying to insert data into a new table from two columns that I am dropping in another table. – Matthew Herbst Jan 13 '19 at 23:31
  • Thank you! This is the updated / recent way to do it! – Ericson Willians Oct 03 '22 at 18:22
6

In sequelize version 4.41.2, when you use ES6+ and you want to do more complex insertions within migration you could make the up an async function which creates your table and then inserts the necessary data into the table. To ensure that the migration either succeeds OR fails without making any changes a transaction is used for every interaction with sequelize. Another important thing to note is that up must return a Promise.

Example of creating a table -> fetching data from other table -> modifying fetched data -> inserting modified data to new table:

module.exports = {
    up: (queryInterface, Sequelize) => queryInterface.sequelize.transaction(async (transaction) => {
        await queryInterface.createTable('person', {
            id: {
                allowNull: false,
                autoIncrement: true,
                primaryKey: true,
                type: Sequelize.INTEGER,
            },
            name: {
                type: Sequelize.STRING,
            },
            age: {
                type: Sequelize.STRING,
            },
        }, { transaction });
        // Returns array [[results], { /** result obj */ }]
        const [dogs] = await queryInterface.sequelize.query('SELECT * FROM public."Dogs";', { transaction });
        // prepare data
        const metamorphed = dogs.map(({ name, age }) => ({
            name,
            age: parseInt((age * 7), 10),
        }));
        return queryInterface.bulkInsert('person', metamorphed, { transaction });
    }),
    down: queryInterface => queryInterface.dropTable('person'),
};
xab
  • 636
  • 7
  • 11
  • Worth mentioning that there's no workaround for the raw SELECT queries currently it seems: https://github.com/sequelize/cli/issues/862 I alwo added a `bulkUpdate` example at: https://stackoverflow.com/questions/54898994/bulkupdate-in-sequelize-orm/69044138#69044138 – Ciro Santilli OurBigBook.com Sep 03 '21 at 14:21
0

I'm Solution. this is an example:

    "use strict";

    module.exports = {
        up: (queryInterface, Sequelize) => {
            return queryInterface
                .createTable("roles", {
                    id: { type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true },
                    name: { type: Sequelize.STRING },
                    description: { type: Sequelize.STRING },
                })
                .then(() => {
                    queryInterface.bulkInsert("roles", [{
                            name: "admin",
                            description: "Admins",
                        },
                        {
                            name: "company",
                            description: "Companies",
                        },
                        {
                            name: "user",
                            description: "Users",
                        },
                    ]);
                });
        },

    down: (queryInterface, Sequelize) => {
        return queryInterface.dropTable("roles");
    },
};
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Sep 29 '21 at 00:47