1. 程式人生 > >Sequelize-nodejs-12-Migrations

Sequelize-nodejs-12-Migrations

Migrations遷移

Just like you use Git / SVN to manage changes in your source code, you can use migrations to keep track of changes to the database. With migrations you can transfer your existing database into another state and vice versa: Those state transitions are saved in migration files, which describe how to get to the new state and how to revert the changes in order to get back to the old state.

You will need Sequelize CLI. The CLI ships support for migrations and project bootstrapping.

就像你使用Git / SVN去管理你的資原始碼的變化,你也能夠使用Migrations去跟蹤你資料庫的變化。使用migration,你可以轉移你已有的資料庫到另一個狀態中,反之亦然:這些狀態轉移將會被記錄在migration檔案中,用以描述如何得到新的狀態和為了回到舊的狀態要如何恢復變化。

你將需要 Sequelize CLI命令列介面支援遷移和專案引導

 

 

The CLI

Installing CLI安裝命令列介面

Let's start with installing CLI, you can find instructions here. Most preferred way is installing locally like this

$ npm install --save sequelize-cli

 

Bootstrapping載入程式

在這之前還要安裝:

npm install --save sequelize mysql2

To create an empty project you will need to execute init

 command

執行init命令來建立空專案

$ node_modules/.bin/sequelize init

終端返回:

userdeMacBook-Pro:test-sequelize user$ node_modules/.bin/sequelize init

Sequelize CLI [Node: 11.1.0, CLI: 5.4.0, ORM: 4.41.2]

Created "config/config.json"
Successfully created models folder at "/Users/user/test-sequelize/models".
Successfully created migrations folder at "/Users/user/test-sequelize/migrations".
Successfully created seeders folder at "/Users/user/test-sequelize/seeders".

This will create following folders

將會生成下面的資料夾

  • config, contains config file, which tells CLI how to connect with database包含配置檔案,它告訴CLI如何連線資料庫
  • models, contains all models for your project包含你的專案的所有模型
  • migrations, contains all migration files 包含所有遷移檔案
  • seeders, contains all seed files包含所有種子檔案

 

Configuration配置

Before continuing further we will need to tell CLI how to connect to database. To do that let's open default config file config/config.json. It looks something like this

在繼續更遠的操作之前,我們需要告訴CLI如何連線資料庫。首先需要開啟預設的配置檔案config/config.json,如下:

{
  "development": {
    "username": "root",
    "password": null,//改成自己資料庫的密碼
    "database": "database_development",//改成sequelize_development
    "host": "127.0.0.1",
    "dialect": "mysql"
  },
  "test": {
    "username": "root",
    "password": null,
    "database": "database_test",//改成sequelize_test
    "host": "127.0.0.1",
    "dialect": "mysql"
  },
  "production": {
    "username": "root",
    "password": null,
    "database": "database_production",//改成sequelize_production
    "host": "127.0.0.1",
    "dialect": "mysql"
  }
}

Now edit this file and set correct database credentials and dialect.

現在編輯此檔案並設定正確的資料庫憑據和語言。

Note: If your database doesn't exists yet, you can just call db:create command. With proper access it will create that database for you.

注意: 如果你的資料庫還不存在,你可以呼叫 db:create 命令。 通過正確的訪問,它將為你建立該資料庫。

 

Creating first Model (and Migration)建立第一個模型(和遷移)

Once you have properly configured CLI config file you are ready to create your first migration. It's as simple as executing a simple command.

一旦你正確配置CLI配置檔案,你就可以建立你的第一個遷移了。它就像執行一個簡單的命令列一樣簡單

We will use model:generate command. This command requires two options

你將使用model:generate命令。該命令需要兩個選項

  • name, Name of the model模型的名字
  • attributes, List of model attributes模型屬性列表

Let's create a model named User.建立模型名為User

$ node_modules/.bin/sequelize model:generate --name User --attributes firstName:string,lastName:string,email:string

終端返回:

userdeMacBook-Pro:test-sequelize user$  node_modules/.bin/sequelize model:generate --name User --attributes firstName:string,lastName:string,email:string

Sequelize CLI [Node: 11.1.0, CLI: 5.4.0, ORM: 4.41.2]

New model was created at /Users/user/test-sequelize/models/user.js .
New migration was created at /Users/user/test-sequelize/migrations/20181205064731-User.js .

This will do following這將發生如下事情:

  • Create a model file user in models folder 在models資料夾中建立了一個user.js模型檔案
  • Create a migration file with name like XXXXXXXXXXXXXX-create-user.js in migrations folder在 migrations 資料夾中建立了一個名字像 XXXXXXXXXXXXXX-create-user.js 的遷移檔案

Note: Sequelize will only use Model files, it's the table representation. On the other hand, the migration file is a change in that model or more specifically that table, used by CLI. Treat migrations like a commit or a log for some change in database.

注意: Sequelize 將只使用模型檔案,該檔案是表描述。另一邊,遷移檔案是該模型的更改,或更具體的是說 CLI 所使用的表。 處理遷移就像是提交或日誌資料庫中的更改。

 

Running Migrations執行遷移

Until this step, we haven't inserted anything into the database. We have just created required model and migration files for our first model User. Now to actually create that table in database you need to run db:migrate command.

直到這一步,我們沒有將任何東西插入資料庫。 我們剛剛為我們的第一個模型 User 建立了必需的模型和遷移檔案。 現在要在資料庫中實際建立該表,需要執行 db:migrate 命令

$ node_modules/.bin/sequelize db:migrate

終端返回:

userdeMacBook-Pro:test-sequelize user$ node_modules/.bin/sequelize db:migrate

Sequelize CLI [Node: 11.1.0, CLI: 5.4.0, ORM: 4.41.2]

Loaded configuration file "config/config.json".
Using environment "development".
sequelize deprecated String based operators are now deprecated. Please use Symbol based operators for better security, read more at http://docs.sequelizejs.com/manual/tutorial/querying.html#operators node_modules/sequelize/lib/sequelize.js:242:13
== 20181205064731-create-user: migrating =======
== 20181205064731-create-user: migrated (0.020s)

This command will execute these steps:此命令將執行這些步驟

  • Will ensure a table called SequelizeMeta in database. This table is used to record which migrations have run on the current database 將在資料庫中確保一個名為 SequelizeMeta 的表。 此表用於記錄在當前資料庫上執行的遷移
  • Start looking for any migration files which haven't run yet. This is possible by checking SequelizeMeta table. In this case it will run XXXXXXXXXXXXXX-create-user.js migration, which we created in last step.開始尋找尚未執行的任何遷移檔案。 這可以通過檢查 SequelizeMeta 表來實現。 在這個例子中,它將執行我們在最後一步中建立的 XXXXXXXXXXXXXX-create-user.js 遷移
  • Creates a table called Users with all columns as specified in its migration file.建立一個名為 User 的表,其中包含其遷移檔案中指定的所有列

 可以檢視連線的資料庫中的確生成了對應的表:

 

 

Undoing Migrations撤消遷移

Now our table has been created and saved in database. With migration you can revert to old state by just running a command.

現在我們的表已建立並儲存在資料庫中。 通過遷移,只需執行命令即可恢復為舊狀態

You can use db:migrate:undo, this command will revert most recent migration.

你可以使用 db:migrate:undo,這個命令將會恢復最近的遷移。

$ node_modules/.bin/sequelize db:migrate:undo

終端返回:

userdeMacBook-Pro:test-sequelize user$ node_modules/.bin/sequelize db:migrate:undo

Sequelize CLI [Node: 11.1.0, CLI: 5.4.0, ORM: 4.41.2]

Loaded configuration file "config/config.json".
Using environment "development".
sequelize deprecated String based operators are now deprecated. Please use Symbol based operators for better security, read more at http://docs.sequelizejs.com/manual/tutorial/querying.html#operators node_modules/sequelize/lib/sequelize.js:242:13
== 20181205064731-create-user: reverting =======
== 20181205064731-create-user: reverted (0.129s)

資料庫將變成:

 

You can revert back to initial state by undoing all migrations with db:migrate:undo:all command. You can also revert back to a specific migration by passing its name in --to option.

通過使用  db:migrate:undo:all 命令撤消所有遷移,可以恢復到初始狀態。 你還可以通過將其名稱傳遞到 --to 選項中來恢復到特定的遷移。

$ node_modules/.bin/sequelize db:migrate:undo:all --to XXXXXXXXXXXXXX-create-posts.js

 

Creating First Seed建立第一個種子

Suppose we want to insert some data into a few tables by default. If we follow up on previous example we can consider creating a demo user for User table.

假設我們希望在預設情況下將一些資料插入到幾個表中。 如果我們跟進前面的例子,我們可以考慮為 User 表建立演示使用者

To manage all data migrations you can use seeders. Seed files are some change in data that can be used to populate database table with sample data or test data.

要管理所有資料遷移,你可以使用 seeders。 種子檔案是資料的一些變化,可用於使用樣本資料或測試資料填充資料庫表

Let's create a seed file which will add a demo user to our User table.

讓我們建立一個種子檔案,它會將一個演示使用者新增到我們的 User 表中(注意,如果你上面撤銷了遷移,要記得恢復回來)

$ node_modules/.bin/sequelize seed:generate --name demo-user

終端返回:

userdeMacBook-Pro:test-sequelize user$ node_modules/.bin/sequelize seed:generate --name demo-user

Sequelize CLI [Node: 11.1.0, CLI: 5.4.0, ORM: 4.41.2]

seeders folder at "/Users/user/test-sequelize/seeders" already exists.
New seed was created at /Users/user/test-sequelize/seeders/20181205071424-demo-user.js .

This command will create a seed file in seeders folder. File name will look something like XXXXXXXXXXXXXX-demo-user.js. It follows the same up / down semantics as the migration files.

這個命令將會在 seeders 資料夾中建立一個種子檔案。檔名看起來像是  XXXXXXXXXXXXXX-demo-user.js。它將像遷移檔案一樣遵循相同的 up/down 語義。

Now we should edit this file to insert demo user to User table.

現在我們應該編輯這個檔案,XXXXXXXXXXXXXX-demo-user.js檔案初始為:

'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, {});
    */
  }
};

將演示使用者插入User表:

'use strict';

module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.bulkInsert('Users', [{
        firstName: 'John',
        lastName: 'Doe',
        email: '[email protected]'
      }], {});
  },

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

 

Running Seeds執行種子

In last step you have create a seed file. It's still not committed to database. To do that we need to run a simple command.

在上一步中,你建立了一個種子檔案。 但它還沒有儲存到資料庫。 為此,我們需要執行一個簡單的命令。

$ node_modules/.bin/sequelize db:seed:all

終端返回:

userdeMacBook-Pro:test-sequelize user$ node_modules/.bin/sequelize db:seed:all

Sequelize CLI [Node: 11.1.0, CLI: 5.4.0, ORM: 4.41.2]

Loaded configuration file "config/config.json".
Using environment "development".
sequelize deprecated String based operators are now deprecated. Please use Symbol based operators for better security, read more at http://docs.sequelizejs.com/manual/tutorial/querying.html#operators node_modules/sequelize/lib/sequelize.js:242:13
== 20181205071424-demo-user: migrating =======

ERROR: Field 'createdAt' doesn't have a default value
ERROR: Field 'updatedAt' doesn't have a default valu

所以在XXXXXXXXXXXXXX-demo-user.js檔案中顯示插入createdAt和updatedAt:

createdAt: new Date(),
updatedAt: new Date()

然後再執行就成功了:

userdeMacBook-Pro:test-sequelize user$ node_modules/.bin/sequelize db:seed:all

Sequelize CLI [Node: 11.1.0, CLI: 5.4.0, ORM: 4.41.2]

Loaded configuration file "config/config.json".
Using environment "development".
sequelize deprecated String based operators are now deprecated. Please use Symbol based operators for better security, read more at http://docs.sequelizejs.com/manual/tutorial/querying.html#operators node_modules/sequelize/lib/sequelize.js:242:13
== 20181205071424-demo-user: migrating =======
== 20181205071424-demo-user: migrated (0.082s)

檢視資料庫可見:

This will execute that seed file and you will have a demo user inserted into User table.

這將執行該種子檔案,你將有一個演示使用者插入 User 表。

Note: Seeders execution is not stored anywhere unlike migrations, which use the SequelizeMeta table. If you wish to override this please read Storage section

注意: seeders 執行不會儲存在任何使用 SequelizeMeta 表的遷移的地方。 如果你想覆蓋這個,請閱讀 Storage部分

 

Undoing Seeds撤銷種子

Seeders can be undone if they are using any storage. There are two commands available for that:

Seeders 如果使用了任何儲存那麼就可以被撤消。 有兩個可用的命令

If you wish to undo most recent seed

如果你想撤消最近的種子

node_modules/.bin/sequelize db:seed:undo

終端返回:

userdeMacBook-Pro:test-sequelize user$ node_modules/.bin/sequelize db:seed:undo

Sequelize CLI [Node: 11.1.0, CLI: 5.4.0, ORM: 4.41.2]

Loaded configuration file "config/config.json".
Using environment "development".
sequelize deprecated String based operators are now deprecated. Please use Symbol based operators for better security, read more at http://docs.sequelizejs.com/manual/tutorial/querying.html#operators node_modules/sequelize/lib/sequelize.js:242:13

但是好像沒有實現什麼操作,資料庫沒有變化,試著呼叫下面的命令看看

If you wish to undo all seeds

如果你想撤消所有的種子

node_modules/.bin/sequelize db:seed:undo:all

 終端返回:

userdeMacBook-Pro:test-sequelize user$ node_modules/.bin/sequelize db:seed:undo:all

Sequelize CLI [Node: 11.1.0, CLI: 5.4.0, ORM: 4.41.2]

Loaded configuration file "config/config.json".
Using environment "development".
sequelize deprecated String based operators are now deprecated. Please use Symbol based operators for better security, read more at http://docs.sequelizejs.com/manual/tutorial/querying.html#operators node_modules/sequelize/lib/sequelize.js:242:13
== 20181205071424-demo-user: reverting =======
== 20181205071424-demo-user: reverted (0.108s)

資料庫變成了:

 

 

 

Advance Topics高階專題

Migration Skeleton遷移框架

The following skeleton shows a typical migration file.以下框架顯示了一個典型的遷移檔案。

module.exports = {
  up: (queryInterface, Sequelize) => {
    // logic for transforming into the new state轉變為新狀態的邏輯
  },

  down: (queryInterface, Sequelize) => {
    // logic for reverting the changes恢復更改的邏輯
  }
}

The passed queryInterface object can be used to modify the database. The Sequelize object stores the available data types such as STRING or INTEGER. Function up or down should return a Promise. Let's look at an example:

傳遞的 queryInterface 物件可以用來修改資料庫。 Sequelize 物件儲存可用的資料型別,如 STRING INTEGER。 函式 up 或 down 應該返回一個 Promise 。 讓我們來看一個例子

module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('Person', {
        name: Sequelize.STRING,
        isBetaMember: {
          type: Sequelize.BOOLEAN,
          defaultValue: false,
          allowNull: false
        }
      });
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable('Person');
  }
}
 

The .sequelizerc File

This is a special configuration file. It lets you specify various options that you would usually pass as arguments to CLI. Some scenarios where you can use it.這是一個特殊的配置檔案。 它允許你指定通常作為引數傳遞給CLI的各種選項。 在某些情況下,你可以使用它。

  • You want to override default path to migrations, models, seeders or config folder.你想要覆蓋到 migrations, models, seeders 或 config 資料夾的路徑
  • You want to rename config.json to something else like database.json
    • 你想要重新命名 config.json 成為別的名字比如 database.json

And a whole lot more. Let's see how you can use this file for custom configuration.還有更多的, 讓我們看一下如何使用這個檔案進行自定義配置。

For starters, let's create an empty file in root directory of your project.對於初學者,可以在專案的根目錄中建立一個空檔案。

$ touch .sequelizerc

Now let's work with an example config.現在可以使用示例配置

const path = require('path');

module.exports = {
  'config': path.resolve('config', 'database.json'),
  'models-path': path.resolve('db', 'models'),
  'seeders-path': path.resolve('db', 'seeders'),
  'migrations-path': path.resolve('db', 'migrations')
}

With this config you are telling CLI to通過這個配置你告訴了CLI

  • Use config/database.json file for config settings使用 config/database.json 檔案來配置設定
  • Use db/models as models folder使用 db/models 作為模型資料夾
  • Use db/seeders as seeders folder使用 db/seeders 作為種子資料夾
  • Use db/migrations as migrations folder使用 db/migrations 作為遷移資料夾

 

Dynamic Configuration動態配置

Configuration file is by default a JSON file called config.json. But sometimes you want to execute some code or access environment variables which is not possible in JSON files.

配置檔案是預設的一個名為 config.json 的JSON檔案。 但有時你想執行一些程式碼或訪問環境變數,這在JSON檔案中是不可能的。

Sequelize CLI can read from both JSON and JS files. This can be setup with .sequelizerc file. Let see how

Sequelize CLI可以從“JSON”和“JS”檔案中讀取。 這可以用.sequelizerc檔案設定。 讓我們來看一下怎麼實現

First you need to create a .sequelizerc file in root folder of your project. This file should override config path to a JS file. Like this

首先,你需要在專案的根資料夾中建立一個 .sequelizerc 檔案。 該檔案應該覆蓋 JS 檔案的配置路徑。 就像

const path = require('path');

module.exports = {
  'config': path.resolve('config', 'config.js')
}

Now Sequelize CLI will load config/config.js for getting configuration options. Since this is a JS file you can have any code executed and export final dynamic configuration file.

現在,Sequelize CLI將載入 config/config.js 以獲取配置選項。 由於這是一個JS檔案,你可以執行任何程式碼並匯出最終的動態配置檔案。

An example of config/config.js file

一個 config/config.js 檔案的例子

const fs = require('fs');

module.exports = {
  development: {
    username: 'database_dev',
    password: 'database_dev',
    database: 'database_dev',
    host: '127.0.0.1',
    dialect: 'mysql'
  },
  test: {
    username: 'database_test',
    password: null,
    database: 'database_test',
    host: '127.0.0.1',
    dialect: 'mysql'
  },
  production: {
    username: process.env.DB_USERNAME,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME,
    host: process.env.DB_HOSTNAME,
    dialect: 'mysql',
    dialectOptions: {
      ssl: {
        ca: fs.readFileSync(__dirname + '/mysql-ca-master.crt')
      }
    }
  }
};

 

Using Environment Variables使用環境變數

With CLI you can directly access the environment variables inside the config/config.js. You can use .sequelizerc to tell CLI to use config/config.js for configuration. This is explained in last section.

使用CLI,你可以直接訪問 config/config.js 內的環境變數。 你可以使用 .sequelizerc 來告訴CLI使用 config/config.js 進行配置。 這在上一節中有所解釋。

Then you can just expose file with proper environment variables.

然後你可以使用正確的環境變數來暴露檔案。

module.exports = {
  development: {
    username: 'database_dev',
    password: 'database_dev',
    database: 'database_dev',
    host: '127.0.0.1',
    dialect: 'mysql'
  },
  test: {
    username: process.env.CI_DB_USERNAME,
    password: process.env.CI_DB_PASSWORD,
    database: process.env.CI_DB_NAME,
    host: '127.0.0.1',
    dialect: 'mysql'
  },
  production: {
    username: process.env.PROD_DB_USERNAME,
    password: process.env.PROD_DB_PASSWORD,
    database: process.env.PROD_DB_NAME,
    host: process.env.PROD_DB_HOSTNAME,
    dialect: 'mysql'
  }

 

Specifying Dialect Options指定語言選項

Sometime you want to specify a dialectOption, if it's a general config you can just add it in config/config.json. Sometime you want to execute some code to get dialectOptions, you should use dynamic config file for those cases.

有時你想指定一個 dialectOption,如果它是一個通用配置,你可以將其新增到 config/config.json中。 有時你想執行一些程式碼來獲取 dialectOptions,你應該為這些情況使用動態配置檔案。

{
    "production": {
        "dialect":"mysql",
        "dialectOptions": {
            "bigNumberStrings": true
        }
    }
}

 

Production Usages生產用途

Some tips around using CLI and migration setup in production environment.

有關在生產環境中使用CLI和遷移設定的一些提示。

1) Use environment variables for config settings. This is better achieved with dynamic configuration. A sample production safe configuration may look like.使用環境變數進行配置設定。 這是通過動態配置更好地實現的。 樣品生產安全配置可能看起來像

const fs = require('fs');

module.exports = {
  development: {
    username: 'database_dev',
    password: 'database_dev',
    database: 'database_dev',
    host: '127.0.0.1',
    dialect: 'mysql'
  },
  test: {
    username: 'database_test',
    password: null,
    database: 'database_test',
    host: '127.0.0.1',
    dialect: 'mysql'
  },
  production: {
    username: process.env.DB_USERNAME,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME,
    host: process.env.DB_HOSTNAME,
    dialect: 'mysql',
    dialectOptions: {
      ssl: {
        ca: fs.readFileSync(__dirname + '/mysql-ca-master.crt')
      }
    }
  }
};

Our goal is to use environment variables for various database secrets and not accidentally check them in to source control.我們的目標是為各種資料庫祕密使用環境變數,而不是意外檢查它們來源控制

 

Storage儲存

There are three types of storage that you can use: sequelize, json, and none.可以使用三種類型的儲存:sequelizejsonnone

  • sequelize : stores migrations and seeds in a table on the sequelize database將遷移和種子儲存在 sequelize 資料庫的表中
  • json : stores migrations and seeds on a json file將遷移和種子儲存在json檔案上
  • none : does not store any migration/seed不儲存任何遷移/種子

Migration Storage遷移儲存

By default the CLI will create a table in your database called SequelizeMeta containing an entry for each executed migration. To change this behavior, there are three options you can add to the configuration file. Using migrationStorage, you can choose the type of storage to be used for migrations. If you choose json, you can specify the path of the file using migrationStoragePath or the CLI will write to the file sequelize-meta.json. If you want to keep the information in the database, using sequelize, but want to use a different table, you can change the table name using migrationStorageTableName.

預設情況下,CLI 將在你的資料庫中建立一個名為 SequelizeMeta 的表,其中包含每個執行遷移的條目。 要更改此行為,可以在配置檔案中新增三個選項。 使用 migrationStorage 可以選擇要用於遷移的儲存型別。 如果選擇 json,可以使用 migrationStoragePath 指定檔案的路徑,或者 CLI 將寫入 sequelize-meta.json 檔案。 如果要將資料儲存在資料庫中,請使用 sequelize,但是要使用其他表格,可以使用 migrationStorageTableName.

{
  "development": {
    "username": "root",
    "password": null,
    "database": "database_development",
    "host": "127.0.0.1",
    "dialect": "mysql",

    // Use a different storage type. Default: sequelize
    "migrationStorage": "json",

    // Use a different file name. Default: sequelize-meta.json
    "migrationStoragePath": "sequelizeMeta.json",

    // Use a different table name. Default: SequelizeMeta
    "migrationStorageTableName": "sequelize_meta"
  }
}

Note: The none storage is not recommended as a migration storage. If you decide to use it, be aware of the implications of having no record of what migrations did or didn't run.注意: 不推薦使用 none 儲存作為遷移儲存。 如果你決定使用它,請注意將會沒有任何移動記錄或沒有執行的記錄.

 

Seed Storage種子儲存

By default the CLI will not save any seed that is executed. If you choose to change this behavior (!), you can use seederStorage in the configuration file to change the storage type. If you choose json, you can specify the path of the file using seederStoragePath or the CLI will write to the file sequelize-data.json. If you want to keep the information in the database, using sequelize, you can specify the table name using seederStorageTableName, or it will default to SequelizeData.

預設情況下,CLI 不會儲存任何被執行的種子。 如果你選擇更改此行為(!),則可以在配置檔案中使用 seederStorage 來更改儲存型別。 如果選擇 json,可以使用 seederStoragePath 指定檔案的路徑,或者 CLI 將寫入檔案 sequelize-data.json。 如果要將資料儲存在資料庫中,請使用 sequelize,你可以使用 seederStorageTableName 指定表名,否則將預設為SequelizeData

{
  "development": {
    "username": "root",
    "password": null,
    "database": "database_development",
    "host": "127.0.0.1",
    "dialect": "mysql",
    // Use a different storage. Default: none
    "seederStorage": "json",
    // Use a different file name. Default: sequelize-data.json
    "seederStoragePath": "sequelizeData.json",
    // Use a different table name. Default: SequelizeData
    "seederStorageTableName": "sequelize_data"
  }
}

 

Configuration Connection String配置連線字串

As an alternative to the --config option with configuration files defining your database, you can use the --url option to pass in a connection string. For example:作為 --config 選項的替代方法,可以使用定義資料庫的配置檔案,你可以使用 --url 選項傳遞連線字串。 例如:

$ node_modules/.bin/sequelize db:migrate --url 'mysql://root:[email protected]_host.com/database_name'

 

Connecting over SSL通過SSL連線

Ensure ssl is specified in both dialectOptions and in the base config.確保ssl在 dialectOptions 和基本配置中指定。

{
    "production": {
        "dialect":"postgres",
        "ssl": true,
        "dialectOptions": {
            "ssl": true
        }
    }
}

 

Programmatic use程式化使用

Sequelize has a sister library for programmatically handling execution and logging of migration tasks.Sequelize 有一個

相關推薦

Sequelize-nodejs-12-Migrations

Migrations遷移 Just like you use Git / SVN to manage changes in your source code, you can use migrations to keep track of changes to the database. With migr

Sequelize-nodejs-13-Working with legacy tables

Working with legacy tables使用遺留表 While out of the box Sequelize will seem a bit opinionated it's trivial to both legacy and forward proof your application

Sequelize-nodejs-11-Raw queries

Raw queries原始查詢 就是使用了原始的查詢語句,如UPDATE users SET y = 42 WHERE x = 12 As there are often use cases in which it is just easier to execute raw / already prepa

Sequelize-nodejs-9-Scopes

Scopes作用域 Scoping allows you to define commonly used queries that you can easily use later. Scopes can include all the same attributes as regular finders,

Sequelize-nodejs-7-Associations

Associations關聯性 This section describes the various association types in sequelize. When calling a method such as User.hasOne(Project), we say that th

Sequelize-nodejs-1-getting started

Sequelize is a promise-based ORM for Node.js v4 and up. It supports the dialects PostgreSQL, MySQL, SQLite and MSSQL and features solid transaction support

egg-sequelize --- nodejs

專案 egg + sequelize + mysql2     專案結構   配置     安裝模組 npm install --save egg-sequelize npm install --

Sequelize 學習筆記(11)- Migrations 遷移

一、作用 類似 git 管理原始碼 一樣,維護你的 DB。 二、安裝 npm install --save sequelize-cli 三、使用 1、構建專案時 node_modules/.bin/sequelize init 會建立以下四個資料夾: config, 包含配置

搭建 nodeJS 伺服器之(2)sequelize

前言 《搭建 nodeJS 伺服器之(2)sequelize》是系列教程的第二部分。包含模型的定義和使用、驗證器,關聯、事務、作用域,鉤子和原始查詢等知識。同時,本系列教程將會帶你從零架構一個五臟俱全的後端專案。 傳送門: 《搭建 nodeJS 伺服器之(1)koa》 - 基於 nodeJs 平臺

Nodejs連線12種資料庫例子集合

轉自:https://segmentfault.com/a/1190000008753686 Cassandra Module: cassandra-driver Installation $ npm install cassandra-driver Exampl

nodejs漸入佳境[12]-node非同步操作

如下非同步程式碼: 12345678910111213 console.log('start...');setTimeout(()=>{  console.log('first callback');},2000)setTimeout(()=>{ &

nodejs -> sequelize -> postgres,你都得設定好時區

背景 最近在做報表統計,因為 sequelize 的時區配置沒加導致了統計數字對不上的問題。 問:大家都知道時區,但是你清楚 UTC 和 GMT 的區別嗎? 答:UTC 是我們現在用的時間標準,GMT 是老的時間計量標準。 (1)GMT 是根據地球的自轉和公轉來計算時間,也就是太陽每天經過位於英國倫敦郊區的

Ubuntu 12.04X64 安裝Nodejs

Nodejs是一個高階貨,安裝過程記錄一下。 安裝Python,GCC,G++ 等環境 1、安裝Python (Ubuntu 預設安裝了Python 2.7.3, 這裡我就不在安裝) 如果你需要安裝,命令如下 sudo apt-get install py

Nodejs ORM框架Sequelize(模型,關聯表,事務,迴圈,及常見問題)

1.建立連線 const Sequelize = require('sequelize'); const sequelize = new Sequelize('database', 'username', 'password', { host: 'host', port: 'port',

Nodejs ORM框架Sequelize快速入門

Nodejs ORM框架Sequelize快速入門 什麼是ORM? 簡單的講就是對SQL查詢語句的封裝,讓我們可以用OOP的方式操作資料庫,優雅的生成安全、可維護的SQL程式碼。直觀上,是一種Model和SQL的對映關係。 const User = sequelize.define('user', {

nodejs 使用資料庫OPM框架 sequelize

安裝sequelize npm install  sequelize//引入框架 var Sequelize = require('sequelize'); //初始化連結(支援連線池) v

nodejs sequelize庫防注入測試

介紹 在nodejs中使用sequlize庫來查詢mysql資料庫, 提供了常用的方法有兩種: 直接查詢sql語句: sequelize.query(); 通過介面,如Project.f

Angularjs學習---angularjs環境搭建,ubuntu 12.04下安裝nodejs、npm和karma

1.下載angularjs 2.示例1 HelloWorld ! 新建一個helloworld.html <!doctype html> <html ng-app> <head> <script src><

nodejs 使用Sequelize操作MySQL,timestamp時間不對問題

這兩天我將工程中的mysql SQL語句改用Sequelize進行序列化操作,遇上了時間不一致的問題,特此記錄下,希望對大家也能有幫助。 我的資料庫中每張表都有自己定義的一個timestamp欄位,取得是current_time,系統當前時間,資料插入後會自動生成此欄位的值

Nodejs連接12種數據庫例子集合

one key .so into god doc lan index mode 原文:https://segmentfault.com/a/1190000008753686 Cassandra Module: cassandra-driver Installati