Lukas Fam
Lukas Fam

Reputation: 21

Sequelize Alter always set all data table foreign key to null

Bug Description

after running sequelize sync with options alter: true, all foreign keys in tables set to null.

await sequelize.sync({ alter: true }).then(async (result) => {
      await initDataUserGroup();
      await initDataUserAdmin();
      await initDataGateType();
});

and here my one model which has foreign key :

const { DataTypes } = require("sequelize");
const { sequelize } = require("../services/DatabaseService");

const UserGroup = require("./UserGroup");
const Biodata = require("./Biodata");

const User = sequelize.define("user", {
  username: {
    type: DataTypes.STRING,
    allowNull: false,
    unique: true,
    validate: {
      notNull: {
        msg: "Username must not be empty",
      },
      notEmpty: true,
    },
  },
  email: {
    type: DataTypes.STRING,
    allowNull: false,
    unique: true,
    validate: {
      notNull: true,
      notEmpty: true,
      isEmail: true,
    },
  },
  password: {
    type: DataTypes.STRING,
    allowNull: false,
    validate: {
      notNull: true,
      notEmpty: true,
    },
  },
});

User.UserGroup = User.belongsTo(UserGroup);
User.Biodata = User.hasOne(Biodata, {
  foreignKey: "userId",
  as: "biodata",
});

module.exports = User;

What do you expect to happen?

It should not set all foreign keys to null after running sync with options { alter: true }

What is actually happening?

userGroupId in table user is null and userId in table biodata is also null.

Environment

From my issue : https://github.com/sequelize/sequelize/issues/13464

anyone can help me please?

Upvotes: 0

Views: 609

Answers (1)

Lukas Fam
Lukas Fam

Reputation: 21

after struggling for a couple of days, I managed to resolve it by disabling and re-enabling foreign keys before and after syncing :

await sequelize.query("PRAGMA foreign_keys = false;");
await sequelize
      .sync({ alter: true })
      .then(async (result) => {
        await initDataUserGroup();
        await initDataGateType();
      })
      .catch((errorMessage) => console.error("sync error = ", errorMessage));
await sequelize.query("PRAGMA foreign_keys = true;");

Feel free to inform me a better solution than the current one.

Upvotes: 1

Related Questions