Migrations

Just like you use version control systems such as Git to manage changes in your source code, you can use migrations to keep track of changes to the database. With migrations you can transfer your existing database into another state and vice versa: Those state transitions are saved in migration files, which describe how to get to the new state and how to revert the changes in order to get back to the old state.

You will need the Sequelize Command-Line Interface (CLI). The CLI ships support for migrations and project bootstrapping.

A Migration in Sequelize is javascript file which exports two functions, up and down, that dictate how to perform the migration and undo it. You define those functions manually, but you don’t call them manually; they will be called automatically by the CLI. In these functions, you should simply perform whatever queries you need, with the help of sequelize.query and whichever other methods Sequelize provides to you. There is no extra magic beyond that.

Installing the CLI

To install the Sequelize CLI:

  1. npm install --save-dev sequelize-cli

For details see the CLI GitHub repository.

Project bootstrapping

To create an empty project you will need to execute init command

  1. npx sequelize-cli init

This will create following folders

  • config, contains config file, which tells CLI how to connect with database
  • models, contains all models for your project
  • migrations, contains all migration files
  • seeders, contains all seed files

Configuration

Before continuing further we will need to tell the CLI how to connect to the database. To do that let’s open default config file config/config.json. It looks something like this:

  1. {
  2. "development": {
  3. "username": "root",
  4. "password": null,
  5. "database": "database_development",
  6. "host": "127.0.0.1",
  7. "dialect": "mysql"
  8. },
  9. "test": {
  10. "username": "root",
  11. "password": null,
  12. "database": "database_test",
  13. "host": "127.0.0.1",
  14. "dialect": "mysql"
  15. },
  16. "production": {
  17. "username": "root",
  18. "password": null,
  19. "database": "database_production",
  20. "host": "127.0.0.1",
  21. "dialect": "mysql"
  22. }
  23. }

Note that the Sequelize CLI assumes mysql by default. If you’re using another dialect, you need to change the content of the "dialect" option.

Now edit this file and set correct database credentials and dialect. The keys of the objects (e.g. “development”) are used on model/index.js for matching process.env.NODE_ENV (When undefined, “development” is a default value).

Sequelize will use the default connection port for each dialect (for example, for postgres, it is port 5432). If you need to specify a different port, use the "port" field (it is not present by default in config/config.js but you can simply add it).

Note: If your database doesn’t exist yet, you can just call db:create command. With proper access it will create that database for you.

Creating the first Model (and Migration)

Once you have properly configured CLI config file you are ready to create your first migration. It’s as simple as executing a simple command.

We will use model:generate command. This command requires two options:

  • name: the name of the model;
  • attributes: the list of model attributes.

Let’s create a model named User.

  1. npx sequelize-cli model:generate --name User --attributes firstName:string,lastName:string,email:string

This will:

  • Create a model file user in models folder;
  • Create a migration file with name like XXXXXXXXXXXXXX-create-user.js in migrations folder.

Note: Sequelize will only use Model files, it’s the table representation. On the other hand, the migration file is a change in that model or more specifically that table, used by CLI. Treat migrations like a commit or a log for some change in database.

Running Migrations

Until this step, we haven’t inserted anything into the database. We have just created required model and migration files for our first model User. Now to actually create that table in database you need to run db:migrate command.

  1. npx sequelize-cli db:migrate

This command will execute these steps:

  • Will ensure a table called SequelizeMeta in database. This table is used to record which migrations have run on the current database
  • Start looking for any migration files which haven’t run yet. This is possible by checking SequelizeMeta table. In this case it will run XXXXXXXXXXXXXX-create-user.js migration, which we created in last step.
  • Creates a table called Users with all columns as specified in its migration file.

Undoing Migrations

Now our table has been created and saved in database. With migration you can revert to old state by just running a command.

You can use db:migrate:undo, this command will revert most recent migration.

  1. npx sequelize-cli db:migrate:undo

You can revert back to initial state by undoing all migrations with db:migrate:undo:all command. You can also revert back to a specific migration by passing its name in --to option.

  1. npx sequelize-cli db:migrate:undo:all --to XXXXXXXXXXXXXX-create-posts.js

Creating the first Seed

Suppose we want to insert some data into a few tables by default. If we follow up on previous example we can consider creating a demo user for User table.

To manage all data migrations you can use seeders. Seed files are some change in data that can be used to populate database table with sample data or test data.

Let’s create a seed file which will add a demo user to our User table.

  1. npx sequelize-cli seed:generate --name demo-user

This command will create a seed file in seeders folder. File name will look something like XXXXXXXXXXXXXX-demo-user.js. It follows the same up / down semantics as the migration files.

Now we should edit this file to insert demo user to User table.

  1. module.exports = {
  2. up: (queryInterface, Sequelize) => {
  3. return queryInterface.bulkInsert('Users', [{
  4. firstName: 'John',
  5. lastName: 'Doe',
  6. email: '[email protected]',
  7. createdAt: new Date(),
  8. updatedAt: new Date()
  9. }]);
  10. },
  11. down: (queryInterface, Sequelize) => {
  12. return queryInterface.bulkDelete('Users', null, {});
  13. }
  14. };

Running Seeds

In last step you have create a seed file. It’s still not committed to database. To do that we need to run a simple command.

  1. npx sequelize-cli db:seed:all

This will execute that seed file and you will have a demo user inserted into User table.

Note: Seeder execution history is not stored anywhere, unlike migrations, which use the SequelizeMeta table. If you wish to change this behavior, please read the Storage section.

Undoing Seeds

Seeders can be undone if they are using any storage. There are two commands available for that:

If you wish to undo the most recent seed:

  1. npx sequelize-cli db:seed:undo

If you wish to undo a specific seed:

  1. npx sequelize-cli db:seed:undo --seed name-of-seed-as-in-data

If you wish to undo all seeds:

  1. npx sequelize-cli db:seed:undo:all

Migration Skeleton

The following skeleton shows a typical migration file.

  1. module.exports = {
  2. up: (queryInterface, Sequelize) => {
  3. // logic for transforming into the new state
  4. },
  5. down: (queryInterface, Sequelize) => {
  6. // logic for reverting the changes
  7. }
  8. }

We can generate this file using migration:generate. This will create xxx-migration-skeleton.js in your migration folder.

  1. npx sequelize-cli migration:generate --name migration-skeleton

The passed queryInterface object can be used to modify the database. The Sequelize object stores the available data types such as STRING or INTEGER. Function up or down should return a Promise. Let’s look at an example:

  1. module.exports = {
  2. up: (queryInterface, Sequelize) => {
  3. return queryInterface.createTable('Person', {
  4. name: Sequelize.DataTypes.STRING,
  5. isBetaMember: {
  6. type: Sequelize.DataTypes.BOOLEAN,
  7. defaultValue: false,
  8. allowNull: false
  9. }
  10. });
  11. },
  12. down: (queryInterface, Sequelize) => {
  13. return queryInterface.dropTable('Person');
  14. }
  15. };

The following is an example of a migration that performs two changes in the database, using an automatically-managed transaction to ensure that all instructions are successfully executed or rolled back in case of failure:

  1. module.exports = {
  2. up: (queryInterface, Sequelize) => {
  3. return queryInterface.sequelize.transaction(t => {
  4. return Promise.all([
  5. queryInterface.addColumn('Person', 'petName', {
  6. type: Sequelize.DataTypes.STRING
  7. }, { transaction: t }),
  8. queryInterface.addColumn('Person', 'favoriteColor', {
  9. type: Sequelize.DataTypes.STRING,
  10. }, { transaction: t })
  11. ]);
  12. });
  13. },
  14. down: (queryInterface, Sequelize) => {
  15. return queryInterface.sequelize.transaction(t => {
  16. return Promise.all([
  17. queryInterface.removeColumn('Person', 'petName', { transaction: t }),
  18. queryInterface.removeColumn('Person', 'favoriteColor', { transaction: t })
  19. ]);
  20. });
  21. }
  22. };

The next example is of a migration that has a foreign key. You can use references to specify a foreign key:

  1. module.exports = {
  2. up: (queryInterface, Sequelize) => {
  3. return queryInterface.createTable('Person', {
  4. name: Sequelize.DataTypes.STRING,
  5. isBetaMember: {
  6. type: Sequelize.DataTypes.BOOLEAN,
  7. defaultValue: false,
  8. allowNull: false
  9. },
  10. userId: {
  11. type: Sequelize.DataTypes.INTEGER,
  12. references: {
  13. model: {
  14. tableName: 'users',
  15. schema: 'schema'
  16. },
  17. key: 'id'
  18. },
  19. allowNull: false
  20. },
  21. });
  22. },
  23. down: (queryInterface, Sequelize) => {
  24. return queryInterface.dropTable('Person');
  25. }
  26. }

The next example is of a migration that uses async/await where you create an unique index on a new column, with a manually-managed transaction:

  1. module.exports = {
  2. async up(queryInterface, Sequelize) {
  3. const transaction = await queryInterface.sequelize.transaction();
  4. try {
  5. await queryInterface.addColumn(
  6. 'Person',
  7. 'petName',
  8. {
  9. type: Sequelize.DataTypes.STRING,
  10. },
  11. { transaction }
  12. );
  13. await queryInterface.addIndex(
  14. 'Person',
  15. 'petName',
  16. {
  17. fields: 'petName',
  18. unique: true,
  19. transaction,
  20. }
  21. );
  22. await transaction.commit();
  23. } catch (err) {
  24. await transaction.rollback();
  25. throw err;
  26. }
  27. },
  28. async down(queryInterface, Sequelize) {
  29. const transaction = await queryInterface.sequelize.transaction();
  30. try {
  31. await queryInterface.removeColumn('Person', 'petName', { transaction });
  32. await transaction.commit();
  33. } catch (err) {
  34. await transaction.rollback();
  35. throw err;
  36. }
  37. }
  38. };

The next example is of a migration that creates an unique index composed of multiple fields with a condition, which allows a relation to exist multiple times but only one can satisfy the condition:

  1. module.exports = {
  2. up: (queryInterface, Sequelize) => {
  3. queryInterface.createTable('Person', {
  4. name: Sequelize.DataTypes.STRING,
  5. bool: {
  6. type: Sequelize.DataTypes.BOOLEAN,
  7. defaultValue: false
  8. }
  9. }).then((queryInterface, Sequelize) => {
  10. queryInterface.addIndex(
  11. 'Person',
  12. ['name', 'bool'],
  13. {
  14. indicesType: 'UNIQUE',
  15. where: { bool : 'true' },
  16. }
  17. );
  18. });
  19. },
  20. down: (queryInterface, Sequelize) => {
  21. return queryInterface.dropTable('Person');
  22. }
  23. }

The .sequelizerc file

This is a special configuration file. It lets you specify the following options that you would usually pass as arguments to CLI:

  • env: The environment to run the command in
  • config: The path to the config file
  • options-path: The path to a JSON file with additional options
  • migrations-path: The path to the migrations folder
  • seeders-path: The path to the seeders folder
  • models-path: The path to the models folder
  • url: The database connection string to use. Alternative to using —config files
  • debug: When available show various debug information

Some scenarios where you can use it:

  • You want to override default path to migrations, models, seeders or config folder.
  • You want to rename config.json to something else like database.json

And a whole lot more. Let’s see how you can use this file for custom configuration.

To begin, let’s create the .sequelizerc file in the root directory of your project, with the following content:

  1. // .sequelizerc
  2. const path = require('path');
  3. module.exports = {
  4. 'config': path.resolve('config', 'database.json'),
  5. 'models-path': path.resolve('db', 'models'),
  6. 'seeders-path': path.resolve('db', 'seeders'),
  7. 'migrations-path': path.resolve('db', 'migrations')
  8. };

With this config you are telling the CLI to:

  • Use config/database.json file for config settings;
  • Use db/models as models folder;
  • Use db/seeders as seeders folder;
  • Use db/migrations as migrations folder.

Dynamic configuration

The configuration file is by default a JSON file called config.json. But sometimes you need a dynamic configuration, for example to access environment variables or execute some other code to determine the configuration.

Thankfully, the Sequelize CLI can read from both .json and .js files. This can be setup with .sequelizerc file. You just have to provide the path to your .js file as the config option of your exported object:

  1. const path = require('path');
  2. module.exports = {
  3. 'config': path.resolve('config', 'config.js')
  4. }

Now the Sequelize CLI will load config/config.js for getting configuration options.

An example of config/config.js file:

  1. const fs = require('fs');
  2. module.exports = {
  3. development: {
  4. username: 'database_dev',
  5. password: 'database_dev',
  6. database: 'database_dev',
  7. host: '127.0.0.1',
  8. port: 3306,
  9. dialect: 'mysql',
  10. dialectOptions: {
  11. bigNumberStrings: true
  12. }
  13. },
  14. test: {
  15. username: process.env.CI_DB_USERNAME,
  16. password: process.env.CI_DB_PASSWORD,
  17. database: process.env.CI_DB_NAME,
  18. host: '127.0.0.1',
  19. port: 3306,
  20. dialect: 'mysql',
  21. dialectOptions: {
  22. bigNumberStrings: true
  23. }
  24. },
  25. production: {
  26. username: process.env.PROD_DB_USERNAME,
  27. password: process.env.PROD_DB_PASSWORD,
  28. database: process.env.PROD_DB_NAME,
  29. host: process.env.PROD_DB_HOSTNAME,
  30. port: process.env.PROD_DB_PORT,
  31. dialect: 'mysql',
  32. dialectOptions: {
  33. bigNumberStrings: true,
  34. ssl: {
  35. ca: fs.readFileSync(__dirname + '/mysql-ca-master.crt')
  36. }
  37. }
  38. }
  39. };

The example above also shows how to add custom dialect options to the configuration.

Using Babel

To enable more modern constructions in your migrations and seeders, you can simply install babel-register and require it at the beginning of .sequelizerc:

  1. npm i --save-dev babel-register
  1. // .sequelizerc
  2. require("babel-register");
  3. const path = require('path');
  4. module.exports = {
  5. 'config': path.resolve('config', 'config.json'),
  6. 'models-path': path.resolve('models'),
  7. 'seeders-path': path.resolve('seeders'),
  8. 'migrations-path': path.resolve('migrations')
  9. }

Of course, the outcome will depend upon your babel configuration (such as in a .babelrc file). Learn more at babeljs.io.

Security tip

Use environment variables for config settings. This is because secrets such as passwords should never be part of the source code (and especially not committed to version control).

Storage

There are three types of storage that you can use: sequelize, json, and none.

  • sequelize : stores migrations and seeds in a table on the sequelize database
  • json : stores migrations and seeds on a json file
  • none : does not store any migration/seed

Migration Storage

By default the CLI will create a table in your database called SequelizeMeta containing an entry for each executed migration. To change this behavior, there are three options you can add to the configuration file. Using migrationStorage, you can choose the type of storage to be used for migrations. If you choose json, you can specify the path of the file using migrationStoragePath or the CLI will write to the file sequelize-meta.json. If you want to keep the information in the database, using sequelize, but want to use a different table, you can change the table name using migrationStorageTableName. Also you can define a different schema for the SequelizeMeta table by providing the migrationStorageTableSchema property.

  1. {
  2. "development": {
  3. "username": "root",
  4. "password": null,
  5. "database": "database_development",
  6. "host": "127.0.0.1",
  7. "dialect": "mysql",
  8. // Use a different storage type. Default: sequelize
  9. "migrationStorage": "json",
  10. // Use a different file name. Default: sequelize-meta.json
  11. "migrationStoragePath": "sequelizeMeta.json",
  12. // Use a different table name. Default: SequelizeMeta
  13. "migrationStorageTableName": "sequelize_meta",
  14. // Use a different schema for the SequelizeMeta table
  15. "migrationStorageTableSchema": "custom_schema"
  16. }
  17. }

Note: The none storage is not recommended as a migration storage. If you decide to use it, be aware of the implications of having no record of what migrations did or didn’t run.

Seed Storage

By default the CLI will not save any seed that is executed. If you choose to change this behavior (!), you can use seederStorage in the configuration file to change the storage type. If you choose json, you can specify the path of the file using seederStoragePath or the CLI will write to the file sequelize-data.json. If you want to keep the information in the database, using sequelize, you can specify the table name using seederStorageTableName, or it will default to SequelizeData.

  1. {
  2. "development": {
  3. "username": "root",
  4. "password": null,
  5. "database": "database_development",
  6. "host": "127.0.0.1",
  7. "dialect": "mysql",
  8. // Use a different storage. Default: none
  9. "seederStorage": "json",
  10. // Use a different file name. Default: sequelize-data.json
  11. "seederStoragePath": "sequelizeData.json",
  12. // Use a different table name. Default: SequelizeData
  13. "seederStorageTableName": "sequelize_data"
  14. }
  15. }

Configuration Connection String

As an alternative to the --config option with configuration files defining your database, you can use the --url option to pass in a connection string. For example:

  1. npx sequelize-cli db:migrate --url 'mysql://root:[email protected]_host.com/database_name'

Programmatic usage

Sequelize has a sister library called umzug for programmatically handling execution and logging of migration tasks.