26

We're using the orm sequelize.js and have defined a model as such:

module.exports = function(sequelize, DataTypes) {
    var Source = sequelize.define('Source', {
        name: {
            type: DataTypes.STRING, 
            allowNull: false, 
            unique: true
        }
    }, {
        paranoid: true
    });

    return Source;
};

This is deployed to production and sync'd to the database using sequelize.sync. Next step, we add a parameter:

module.exports = function(sequelize, DataTypes) {
    var Source = sequelize.define('Source', {
        name: {
            type: DataTypes.STRING, 
            allowNull: false, 
            unique: true
        }, 
            location: {
                    type: DataTypes.STRING
            }
    }, {
        paranoid: true
    });

    return Source;
};

However, when deploying to production sequelize.sync does not add this new parameter. This is because sync does a:

CREATE TABLE IF NOT EXISTS

And does not actually update the schema if the table exists. This is noted in their documentation.

The only option seems to be to { force: true }, however this is not okay for a production database.

Does anyone know how to properly update the schema when changes are necessary?

BlaM
  • 28,465
  • 32
  • 91
  • 105
Matt
  • 5,547
  • 23
  • 82
  • 121

2 Answers2

29

You want to implement Sequelize migrations:

http://docs.sequelizejs.com/manual/tutorial/migrations.html

These will enable you to transition developer, staging, and production databases between known states.

abernier
  • 27,030
  • 20
  • 83
  • 114
Dan Kohn
  • 33,811
  • 9
  • 84
  • 100
  • 1
    I have a question around this. I can use sequelize-cli to create a new model and its corresponding migration script using sequelize model:create which creates a model and the migration script, is there any way same can be done when adding new columns or constraints. Do we have to manually write the migration scripts for these tasks or is there any way to auto generate the migration scripts. – Zeeshan Jan Jul 12 '15 at 03:11
  • 3
    that is the problem with sequelize we have to write manually mig scripts geez ! – Rizwan Patel Sep 12 '16 at 11:33
  • Here is an example migration https://github.com/abelnation/sequelize-migration-hello – remjx Dec 30 '18 at 13:03
5

A quicker way would be using {alter: true} option.

Ref: https://sequelize.org/master/class/lib/sequelize.js~Sequelize.html#instance-method-sync

4b0
  • 21,981
  • 30
  • 95
  • 142
Saro
  • 810
  • 2
  • 12
  • 22
  • 3
    The documentation says that it's not recommended in production: `Not recommended for production use. Deletes data in columns that were removed or had their type changed in the model.` – articga Nov 24 '19 at 14:58
  • 1
    Also there is an `alter.drop` option: `Prevents any drop statements while altering a table when set to false` – MortezaE Sep 29 '20 at 17:04