首先要先建立用來進行 database migrations 的專案,sequelize有提供一個cli套件可以讓我們方便的建立 migrations,步驟如下:
mkdir dbMigrations
cd dbMigrations
npm init
npm install --save-dev mysql2 sequelize sequelize-cli
npx sequelize-cli init
npx sequelize-cli migration:generate --name init
Sequelize CLI [Node: 14.19.1, CLI: 6.5.1, ORM: 6.24.0]
migrations folder at "/root/workspace/probability/dbMigrations/migrations" already exists.
New migration was created at /root/workspace/probability/dbMigrations/migrations/20221005094912-init.js .
可以看到產生了/root/workspace/probability/dbMigrations/migrations/20221005094912-init.js
這隻遷移檔案
20221005094912-init.js
'use strict';
/** @type {import('sequelize-cli').Migration} */
module.exports = {
async up (queryInterface, Sequelize) {
/**
* Add altering commands here.
*
* Example:
* await queryInterface.createTable('users', { id: Sequelize.INTEGER });
*/
},
async down (queryInterface, Sequelize) {
/**
* Add reverting commands here.
*
* Example:
* await queryInterface.dropTable('users');
*/
}
};
'use strict';
/** @type {import('sequelize-cli').Migration} */
module.exports = {
async up(queryInterface, Sequelize) {
/**
* Add altering commands here.
*
* Example:
* await queryInterface.createTable('users', { id: Sequelize.INTEGER });
*/
await queryInterface.sequelize.query(`
CREATE TABLE users (
id bigint(20) NOT NULL AUTO_INCREMENT COMMENT '編號',
parent int(11) NULL DEFAULT NULL COMMENT '父帳號',
is_banned tinyint(1) NULL DEFAULT FALSE COMMENT '是否被封停',
account varchar(20) NULL DEFAULT NULL COMMENT '名稱',
password varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '密碼',
created_time timestamp(0) NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '創建時間',
updated_time timestamp(0) NULL COMMENT '更新時間',
created_name varchar(20) NULL COMMENT '創建人員',
updated_name varchar(20) NULL COMMENT '更新人員',
PRIMARY KEY (id) USING BTREE,
UNIQUE INDEX index_agent(account) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = COMPACT;`);
},
async down(queryInterface, Sequelize) {
/**
* Add reverting commands here.
*
* Example:
* await queryInterface.dropTable('users');
*/
await queryInterface.dropTable('users');
},
};
接著我們就可以在專案根目錄底下進行,版本遷移。
npx sequelize-cli db:migrate // 版本推進
npx sequelize-cli db:migrate:undo // 版本退回
操作了進版之後我們可以看到 mysql 裡面產生了兩個表單
退版亦然,會記錄在SequelizeMeta裡面,這樣我們就可以透過這個紀錄清楚明白的知道我們曾經對database進行了甚麼樣的操作,之後我們對於資料庫的版本就也能好好的控管了。