Sagi Rika
Sagi Rika

Reputation: 2979

how to use migrations properly

My question is a bit abstract, but I hope that not too much.

I am building a project that's using Sequelize as it's ORM. It's already in production, meaning I have data in my database that CANNOT be deleted. Since we still develop, I sometimes need to change the database (alter a column, add a column, delete a column).

In the project I am using sequelize.sync(). The only option to enforce changes in database is with sequelize.sync({force: true}), but this command deletes all data from database.

To my understanding I need to use migrations. Sadly, I have read the documentation and looked in Stack Overflow and I still couldn't find a proper guide on how to do a migration and keep your data.

Let's say I have a model, User:

module.exports = (sequelize, DataTypes) => {
  var Users = sequelize.define('user', {
    id: {
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
      primaryKey: true
    },
    username: {
      type: DataTypes.STRING(20),
      unique: {
        msg: 'A person with the same username already exists!'
      },
      allowNull: false
    }, 
    password: {
      type: DataTypes.STRING(100),
      allowNull: false
    },
    phone: {
      type: DataTypes.STRING(50),
      allowNull: true,
      unique: {
        msg: 'A user with the same phone number already exists!'
      }
    }
  });

  Users.associate = function (models) {
    models.user.User_roles = models.user.belongsTo(models.user_role, {foreignKey: 'role'});

    models.user.Site_access = models.user.hasMany(models.site_access, {
      as: 'site_access',
      onDelete: "CASCADE",
      foreignKey: {
        allowNull: false
      }
    });
  };
  return Users;
};

Say I wanted to add a column birthday TIMESTAMP without erasing all existing data, how can I do so?

Upvotes: 0

Views: 111

Answers (2)

bach942
bach942

Reputation: 87

As an alternative also you can use the Sequelize CLI instead of using the models sync. This allows you to also create more complicated migrations, with rollbacks, and seeders along with your models.

Upvotes: 0

kkangil
kkangil

Reputation: 1746

Add columns in your User table and use alter

sequelize.sync({
    force: false,
    alter: true
 })

The alter true is gonna only update new columns or deleted columns without delete datas.

Upvotes: 1

Related Questions