シーケンスの移行を使用して新しい非NULL、一意の列を追加する


この短い記事は、あなたが新しいnon-null and unique 既存のリレーショナルデータベースのカラムsequelize NODEJSにおける移行

Note: This is for development environments and not recommended for production.


アプリケーションを書いている間、既存のデータベースに新しい非NULLと一意の列を追加する必要があるかもしれません.現在のテーブルを削除せずに、私のデモプロジェクトでは、Sequelize ORMを使用しています.

問題記述


我々にはusers 次の列を使用したテーブルを作成しますusername テーブルを削除せずに一意でNULLでなければならないカラム.
| id | name  | email                 | age | hobby   |
|----|-------|-----------------------|-----|---------|
| 1  | bob   | [email protected]          | 23  | coding  |
| 2  | alice | [email protected]   | 25  | dance   |
| 3  | John  | [email protected]   | 22  | singing |
| 4  | frank | [email protected]      | 28  | reading |

解決策


つの簡単な解決策は、挿入することですemail フィールドusername 列は両方ともユニークですが、一般的な例を取ります.
を使って移行ファイルを作りましょうsequelize-cli
npx sequelize migration:create --name=add_username_users
擬似コードの画面キャプチャ

まず説明するにはまずusername ちょうどコラムunique その成功に対する制約は、新たに追加されたすべての行を更新するロジックを書きますusername あなたが好きなロジックを持つ列.使用する{ type: QueryTypes.SELECT } インSELECT クエリはここでメタデータを必要としないため、クエリの結果を配列で取得します.not-null 制約.順序の移行のダウン部分についてはusername カラム.
私の最終的なコードは、ランダムに生成されたユーザー名で新しいコラムを追加することです.
const { QueryTypes } = require('sequelize');
module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.addColumn('users','username',{
      type: Sequelize.STRING,
      unique: true
    }).then((data) => {
      queryInterface.sequelize
        .query(`SELECT id from users`, {
          type: QueryTypes.SELECT
        })
        .then((rows) => {
          rows.map((row) => {
            queryInterface.sequelize.query(
              `UPDATE users SET username='${Math.random()
                .toString(36).substr(2, 8)}' WHERE id=${row.id};`
            );
          });
          Promise.resolve();
        })
        .then(() => {
          queryInterface.changeColumn('users', 'username', {
            type: Sequelize.STRING,
            allowNull: false
          });
        });
    })
  },
  down: async (queryInterface, Sequelize) => {
    await queryInterface.removeColumn('users', 'username');
  }
};
読んでくださってありがとうございます.
参考文献
ランダム生成:stackOverflow answer
コードアイデアsequelize github issue