Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize: Changing model schema on production

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?

like image 936
Matt Avatar asked Jul 17 '13 19:07

Matt


People also ask

Is Sequelize good for production?

The documentation for Sequelize states that sequelize. sync() shoudln't be used on production, as it is potentially destructive.

How do I update a Sequelized model?

The Model. upsert() method is a new method added in Sequelize v6 that allows you to perform an update statement only when a row with matching values already exist. To update a row, you need to specify the primary key of the row, which is the id column in case of the Users table.


2 Answers

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.

like image 119
Dan Kohn Avatar answered Sep 18 '22 13:09

Dan Kohn


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

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

like image 29
Saro Avatar answered Sep 19 '22 13:09

Saro