詳解sequelize-cli管理數(shù)據(jù)庫

Sequelize遷移來幫助我們跟蹤數(shù)據(jù)庫的更改,并在各個不同時期的數(shù)據(jù)庫狀態(tài)之間進(jìn)行切換

新建文件夾 seq 通過命令行工具進(jìn)入該文件夾下

npm init --yes

會生成一個package.json

1. 安裝

npm i sequelize-cli --save-dev

sequelize-cli 的依賴是 sequelize sequelize的依賴是mysql2 需要自己手動安裝

然后安裝

npm i sequelize

我要用mysql演示 安裝mysql2

npm i mysql2

我們是局部安裝所以執(zhí)行時需要這樣

./node_modules/.bin/sequelize-cli --version
# 或者
./node_modules/.bin/sequelize --version

利用npx可以這樣子寫(npx教程

npx sequelize-cli --version
# 或者
npx sequelize --version

先執(zhí)行看看所有命令了解

npx sequelize
image

2. 初始化

sequelize init

初始化sequelize項目,該命令將創(chuàng)建如下目錄:

  • config:包含配置文件,它告訴CLI如何連接數(shù)據(jù)庫

  • models:包含您的項目的所有模型

  • migrations:包含所有遷移文件 (數(shù)據(jù)表結(jié)構(gòu)

  • seeders:包含所有種子文件 (具體數(shù)據(jù)

image

優(yōu)先打開config下的config.json

{
  "development": {
    "username": "root",
    "password": "123456",
    "database": "list",
    "host": "127.0.0.1",
    "dialect": "mysql",
    "operatorsAliases": false
  },
  "test": {
    "username": "root",
    "password": null,
    "database": "database_test",
    "host": "127.0.0.1",
    "dialect": "mysql",
    "operatorsAliases": false
  },
  "production": {
    "username": "root",
    "password": null,
    "database": "database_production",
    "host": "127.0.0.1",
    "dialect": "mysql",
    "operatorsAliases": false
  }
}

配置在不同環(huán)境下數(shù)據(jù)庫連接和密碼 dialect 是你要操作的數(shù)據(jù)庫類型,當(dāng)前我使用的是mysql 也就是說sequelize支持什么數(shù)據(jù)庫他就支持啥數(shù)據(jù)庫, 默認(rèn)當(dāng)前環(huán)境為開發(fā)環(huán)境

config.json配置完成后

3. 創(chuàng)建數(shù)據(jù)庫和刪除數(shù)據(jù)庫

npx sequelize db:create

他會根據(jù)你config.json 中添加的數(shù)據(jù)名稱創(chuàng)建

出師不利,立馬報錯了。如下顯示。就是告訴你這個版本不需要這條。請刪掉

image

那就刪除config.json中的

"operatorsAliases": false

再執(zhí)行。成功創(chuàng)建

image

執(zhí)行刪除

npx sequelize db:drop list
image

刪除成功

記得再安裝回來測試接下來操作。。。

4. 創(chuàng)建模型文件 model

model:generate / model:create

創(chuàng)建一個模型文件

-- name:模型名稱,必須

-- attributes:字段列表,必須

新建一個表名為user 字段有username 和sex的表模型,運(yùn)行以下命令

npx sequelize model:generate --name user --attributes username:string,sex:string
image
  • 在 models 文件夾中創(chuàng)建了一個 user 模型文件(供程序使用)

  • 在 migrations 文件夾中創(chuàng)建了一個名字像 xxxxxxxx-create-user.js 的遷移文件(供遷移使用)

image

user.js 文件

'use strict';
module.exports = (sequelize, DataTypes) => {
  const user = sequelize.define('user', {
    username: DataTypes.STRING,
    sex: DataTypes.STRING
  }, {});
  user.associate = function(models) {
    // associations can be defined here
  };
  return user;
};

202006050222227-create-user.js

'use strict';
module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('users', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      username: {
        type: Sequelize.STRING
      },
      sex: {
        type: Sequelize.STRING
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable('users');
  }
};

文件雖然建完了,但是數(shù)據(jù)庫里卻啥也沒有

image

需要執(zhí)行以下命令才能寫入數(shù)據(jù)庫

也就是我們核心要做的執(zhí)行遷移

5. 執(zhí)行遷移

所謂遷移,就是對數(shù)據(jù)庫進(jìn)行結(jié)構(gòu)的創(chuàng)建,升級(修改)等操作

db:migrate

  • 會在數(shù)據(jù)庫中創(chuàng)建一個 SequelizeMeta 表,用于記錄每次的遷移記錄

  • 執(zhí)行 migrations 文件下的滿足條件(SequelizeMeta表)的腳本

px sequelize db:migrate
image

看數(shù)據(jù)庫

image

而且還多了一個SequelizeMeta的表記錄遷移記錄

image

如果再執(zhí)行一次遷移文件會不會對數(shù)據(jù)庫造成更改呢?答案是否定的,不會的

image

看一下當(dāng)前狀態(tài)

npx sequelize db:migrate:status

既然能寫入一定還能恢復(fù),否則就失去意義了

6.回退遷移操作

撤銷遷移

db:migrate:undo - 撤銷上一次的遷移操作

db:migrate:undo:all - 撤銷所有的遷移操作

db:migrate:undo --name 具體遷移腳本

測試

npx sequelize db:migrate:undo
image

此時狀態(tài)

image

重要:這就說明了,如果當(dāng)前文件未被執(zhí)行過,狀態(tài)為down 執(zhí)行過則為 up

當(dāng)你執(zhí)行遷移時執(zhí)行的是遷移js文件中的,up函數(shù)。反之則是down函數(shù) (這里可以仔細(xì)看一下migrations文件夾下的文件具體函數(shù))

遷移文件和種子文件都是有工具初始化,自己編寫

queryInterface文檔: https://sequelize.org/master/class/lib/dialects/abstract/query-interface.js~QueryInterface.html

包括增加字段,刪除字段,還有種子文件要用到增加數(shù)據(jù)等

舉例說明

先執(zhí)行了剛才的遷移文件

這是當(dāng)前users表里的結(jié)構(gòu)

image

我們現(xiàn)在要添加一個字段 lastname

新建一個遷移文件

npx sequelize migration:create --name addLastname

image

打開生成的這個js文件 改寫

'use strict';

module.exports = {
  up: (queryInterface, Sequelize) => {
    /*
      Add altering commands here.
      Return a promise to correctly handle asynchronicity.

      Example:
      return queryInterface.createTable('users', { id: Sequelize.INTEGER });
    */
    return queryInterface.addColumn('user', 'lastname', Sequelize.STRING);
  },

  down: (queryInterface, Sequelize) => {
    /*
      Add reverting commands here.
      Return a promise to correctly handle asynchronicity.

      Example:
      return queryInterface.dropTable('users');
    */
    return queryInterface.removeColumn('user', 'lastname', Sequelize.STRING);
  }
};

執(zhí)行遷移操作

image
image

成功,其他操作api查看文檔

queryInterface文檔: https://sequelize.org/master/class/lib/dialects/abstract/query-interface.js~QueryInterface.html

7. 種子文件

種子文件

遷移文件是用來構(gòu)建數(shù)據(jù)庫以及表結(jié)構(gòu)的,種子文件是用來構(gòu)建數(shù)據(jù)的

seed:generate --name demo-user (自定義的名字)

種子文件腳本與遷移腳本類似,由up于down函數(shù)組成,傳入的參數(shù)也是一致的

先生成種子文件 name 后邊接的是自定義的名字

npx sequelize seed:generate --name userseed
image
image

打開這個文件

'use strict';

module.exports = {
  up: (queryInterface, Sequelize) => {
    /*
      Add altering commands here.
      Return a promise to correctly handle asynchronicity.

      Example:
      return queryInterface.bulkInsert('People', [{
        name: 'John Doe',
        isBetaMember: false
      }], {});
    */
  },

  down: (queryInterface, Sequelize) => {
    /*
      Add reverting commands here.
      Return a promise to correctly handle asynchronicity.

      Example:
      return queryInterface.bulkDelete('People', null, {});
    */
  }
};

很明顯是空的,想要添加數(shù)據(jù)需要自己寫

測試添加一條數(shù)據(jù)

'use strict';

module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.bulkInsert('users', [{
      username: 'John Doe',
      sex: 'man',
      lastname: 'hello',
      createdAt: '2020-06-09 11:56:21',
      updatedAt: '2020-06-09 11:56:21'
    }], {});
  },

  down: (queryInterface, Sequelize) => {
    return queryInterface.bulkDelete('users', null, {});
  }
};

執(zhí)行種子

db:seed 指定種子文件 運(yùn)行指定種子文件

db:seed:all 運(yùn)行所有種子文件

npx sequelize db:seed:all
image

看數(shù)據(jù)庫

image

8. 撤銷種子執(zhí)行

db:seed:undo --seed 指定種子文件 撤銷指定種子文件

db:seed:undo:all 撤銷所有種子文件

npx sequelize db:seed:undo:all
image

數(shù)據(jù)庫中剛才添加的數(shù)據(jù)不見了。

9.種子存儲記錄

存儲記錄

默認(rèn)情況下seed不記錄過程,如果需要記錄則需要單獨設(shè)置,在配置文件config.json中增加

seederStorage

存儲引擎:none、json、mongodb、sequelize

seederStoragePath 存儲路徑(json有效)

seederStorageTableName 存儲表名,mongodb和sequelize有效

舉一個例子

config.json

{
  "development": {
    "username": "root",
    "password": "123456",
    "database": "list",
    "host": "127.0.0.1",
    "dialect": "mysql",
    "seederStorage": "json",
    "seederStoragePath": "./seeder.json"
  },
  "test": {
    "username": "root",
    "password": null,
    "database": "database_test",
    "host": "127.0.0.1",
    "dialect": "mysql"
  },
  "production": {
    "username": "root",
    "password": null,
    "database": "database_production",
    "host": "127.0.0.1",
    "dialect": "mysql"
  }
}
image

然后我們在執(zhí)行種子文件

image

這時候多出個文件

image

打開seeder.json

[
  "20200605031821-userseed.js"
]

這個類似于我們SequelizeMeta表中的內(nèi)容

image

10. 關(guān)于文檔查看

https://sequelize.org/master/

在左側(cè)列表里找

image

即可找到 sequelize-cli 相關(guān)的文檔。

sequelize其他Api

https://sequelize.org/master/identifiers.html

源文章來源:https://www.cnblogs.com/jianghaijun4031/p/13231846.html

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容