Question

Can somebody please give me some complete examples for sequelize migrations for nodejs as the actual documentation itself doesn't give the complete example of how it is to be done.

or may be give a complete example of some other module that can be used and best practise of how to be use in heroku?

Thanks

Was it helpful?

Solution

When you initialize sequelize locally by running:

sequelize -i

a migration folder, config folder, and config.json inside the config folder are created. That json file is where you set the environments of your application. Here is an example of a config.json file.

{
  "development": {
  "username": "postgres",
  "password": "password",
  "database": "dbname",
  "host": "100.0.0.0",
  "dialect":"postgres",
  "protocol":"postgres",
  "port":"xxxx"
 },
  "staging": {
  "username": "dbusername",
  "password": "dbpassword",
  "database": "db",
  "host": "host",
  "dialect":"postgres",
  "protocol":"postgres",
  "port":"xxxx"
  },
  "production": {
  "username": "dbusername",
  "password": "dbpassword",
  "database": "db",
  "host": "dbhost",
  "dialect":"postgres",
  "protocol":"postgres",
  "port":"xxxx"
  }
}

The production object is where you set your heroku production app database variables. You can access them by running the following in the command line:

heroku config --app production-app-name

All the variables will be in the database_url config var you set.

When you're ready to run a migration, all you run in the command line then is:

heroku run sequelize db:migrate --env production -m --app production-app-name. 

--env will be whichever database object in config.json you want migrated.

Instead of embedding passwords in a file, use this handy sequelize capability:

"production": {
  "use_env_variable": "DATABASE_URL"
}

OTHER TIPS

You can use the Procfile and put this at the top.

release: npx sequelize-cli db:migrate

Then you will need a .sequelizerc file to define where your migrations are.

And for the config you can use this for ssl.

production: {
 use_env_variable: 'DATABASE_URL',
 dialect: 'postgres',
 protocol: 'postgres',
 ssl: true,
 dialectOptions: {
   ssl: {
    require: true,
    rejectUnauthorized: false,
   },
 },
}

Since March 2019, Heroku runs build npm script after each deploy. Improving the amazing comment above, you can add sequelize migration to it (locate in the package.json file, on root):

...
"scripts": {
  ...
  "build": "sequelize db:migrate --env production && <other stuff to do before run the app>"
}
...

Do you have a custom config sequelize file ? Watch out. You have to take care of it. In my case i should have done this command :

heroku run npx sequelize-cli db:migrate --config sequelize-config.js --app your-app --env production

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top