续集不会创建唯一约束

时间:2018-07-07 20:14:44

标签: postgresql sequelize.js unique-constraint sequelize-cli

我正在尝试使用sequelize在postgres DB中的多个列上创建唯一约束。说明here很清楚,但是不起作用。这是我的迁移文件的样子:

module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('scores', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      opp: {
        type: Sequelize.INTEGER,
        allowNull: false,
        unique: 'compositeScoreIndex'
      },
      oppt: {
        type: Sequelize.STRING,
        allowNull: false,
        unique: 'compositeScoreIndex'
      },
      tree: {
        type: Sequelize.STRING,
        allowNull: false,
        unique: 'compositeScoreIndex'
      },
      version: {
        type: Sequelize.INTEGER,
        allowNull: false,
        unique: 'compositeScoreIndex'
      },
      score: {
        type: Sequelize.JSON,
        allowNull: false
      }
    }, {
      indexes: [{
          unique: true,
          fields: ['opp', 'oppt', 'tree', 'version']
      }]
    });
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable('scores');
  }
};

这应该等同于以下查询:

CREATE TABLE scores (id INT PRIMARY KEY NOT NULL, opp INT NOT NULL,
oppt TEXT NOT NULL, tree TEXT NOT NULL, version INT NOT NULL, score
JSON NOT NULL, CONSTRAINT uniq_scores UNIQUE(opp, oppt, tree, version));

但是连续迁移无法创建约束。我可以在opp,oppt,tree和version中创建具有相同值的多行。还有其他人看到吗?

更新:我能够使迁移打印出SQL查询的日志语句。这是与上述迁移文件一起运行的CREATE TABLE查询:

CREATE TABLE IF NOT EXISTS "scores" ("id"   SERIAL , "oppId" INTEGER NOT NULL,
"oppType" VARCHAR(255) NOT NULL, "tree" VARCHAR(255) NOT NULL,
"version" INTEGER NOT NULL, "score" JSON NOT NULL, "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL,
"updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL, PRIMARY KEY ("id"));

很显然,这里没有提到唯一约束。任何人都知道为什么Sequelize在这里表现不如预期吗?

0 个答案:

没有答案