Sequelize
這是主要的類別,是 sequelize 的進入點。
靜態方法摘要
靜態公開方法 | ||
public static |
一個 AND 查詢 |
自 v2.0.0-dev3 版本起 |
public static |
建立一個表示呼叫 cast 函數的物件。 |
自 v2.0.0-dev3 版本起 |
public static |
建立一個代表資料庫中欄位的物件,這允許您在查詢中引用另一個欄位。 |
自 v2.0.0-dev3 版本起 |
public static |
建立一個表示資料庫函數的物件。 |
自 v2.0.0-dev3 版本起 |
public static |
為 postgres/sqlite/mysql json 資料類型建立表示巢狀 where 條件的物件。 |
|
public static |
建立一個表示字面值的物件,例如: |
自 v2.0.0-dev3 版本起 |
public static |
一個 OR 查詢 |
自 v2.0.0-dev3 版本起 |
public static |
將 CLS(持續本地儲存)與 Sequelize 一起使用。 |
|
public static |
指定 attr = condition 的一種方式。 |
自 v2.0.0-dev3 版本起 |
建構子摘要
公開建構子 | ||
public |
constructor(database: string, username: string, password: string, options: object) 使用資料庫名稱、使用者名稱和密碼來實例化 sequelize。 |
成員摘要
公開成員 | ||
public |
models: {} 模型以給予 |
方法摘要
公開方法 | ||
public |
async authenticate(options: object): Promise 透過嘗試驗證來測試連線。 |
|
public |
關閉此 sequelize 實例使用的所有連線,並釋放所有引用,以便可以垃圾回收該實例。 |
|
public |
async createSchema(schema: string, options: object): Promise 建立新的資料庫結構描述。 |
|
public |
定義一個新的模型,表示資料庫中的一個表格。 |
|
public |
刪除透過此 sequelize 實例定義的所有表格。 |
|
public |
async dropAllSchemas(options: object): Promise 刪除所有結構描述。 |
|
public |
async dropSchema(schema: string, options: object): Promise 刪除單一結構描述 |
|
public |
逸出值。 |
|
public |
傳回資料庫名稱。 |
|
public |
getDialect(): string 傳回指定的方言。 |
|
public |
傳回 QueryInterface 的實例。 |
|
public |
檢查是否已定義具有給定名稱的模型 |
|
public |
擷取已定義的模型 |
|
public |
在資料庫上執行查詢,可選擇繞過所有 Sequelize 的優點。 |
|
public |
根據方言取得隨機的 fn |
|
public |
執行一個會設定環境或使用者變數的查詢。 |
|
public |
async showAllSchemas(options: object): Promise 顯示所有已定義的結構描述 |
|
public |
將所有已定義的模型同步到資料庫。 |
|
public |
async transaction(options: object, autoCallback: Function): Promise 開始一個交易。 |
|
public |
截斷透過 sequelize 模型定義的所有資料表。 |
靜態公開方法
public static cast(val: any, type: string): cast 自 v2.0.0-dev3 起 原始碼
建立一個表示呼叫 cast 函數的物件。
參數
名稱 | 型別 | 屬性 | 描述 |
val | any | 要轉換的值 |
|
type | string | 要轉換成的型別 |
public static col(col: string): col 自 v2.0.0-dev3 起 原始碼
建立一個代表資料庫中欄位的物件,這允許在查詢中參考另一個欄位。這通常與 sequelize.fn
一起使用很有用,因為 fn 的原始字串參數會被跳脫。
參數
名稱 | 型別 | 屬性 | 描述 |
col | string | 欄位的名稱 |
請參閱
- Sequelize#fn
public static fn(fn: string, args: any): fn 自 v2.0.0-dev3 起 原始碼
建立一個代表資料庫函式的物件。這可以用在搜尋查詢中,包括 where 和 order 部分,以及欄位定義中的預設值。如果想要在函式中參考欄位,應該使用 sequelize.col
,以便欄位被正確地解釋為欄位而不是字串。
參數
名稱 | 型別 | 屬性 | 描述 |
fn | string | 想要呼叫的函式 |
|
args | any | 所有後續參數都將作為參數傳遞給函式 |
範例
instance.update({
username: sequelize.fn('upper', sequelize.col('username'))
});
public static json(conditionsOrPath: string | object, value: string | number | boolean): json 原始碼
為 postgres/sqlite/mysql json 資料類型建立表示巢狀 where 條件的物件。
public static literal(val: any): literal 自 v2.0.0-dev3 起 原始碼
建立一個代表常值的物件,也就是不會被跳脫的內容。
參數
名稱 | 型別 | 屬性 | 描述 |
val | any | 常值的值 |
public static useCLS(ns: object): object 原始碼
將 CLS(持續本地儲存)與 Sequelize 一起使用。透過持續本地儲存,交易回呼中的所有查詢都會自動接收交易物件。
提供的 CLS 命名空間會儲存為 Sequelize._cls
參數
名稱 | 型別 | 屬性 | 描述 |
ns | object | CLS 命名空間 |
public static where(attr: object, comparator: symbol, logic: string | object): * 自 v2.0.0-dev3 起 原始碼
指定 attr = condition 的一種方式。
attr 可以是從 Model.rawAttributes
取得的物件(例如 Model.rawAttributes.id
或 Model.rawAttributes.name
)。該屬性應在模型定義中定義。該屬性也可以是來自 sequelize 工具函式之一的物件 (sequelize.fn
, sequelize.col
等)。
對於字串屬性,請使用常規的 { where: { attr: something }}
語法。 如果不希望字串被跳脫,請使用 sequelize.literal
。
回傳
* |
公開建構子
public constructor(database: string, username: string, password: string, options: object) 原始碼
使用資料庫名稱、使用者名稱和密碼來實例化 sequelize。
參數
名稱 | 型別 | 屬性 | 描述 |
database | string |
|
資料庫的名稱 |
username | string |
|
用於向資料庫驗證的使用者名稱。 |
password | string |
|
用於向資料庫驗證的密碼。支援 SQLite 的 SQLCipher 加密。 |
options | object |
|
具有選項的物件。 |
options.host | string |
|
關聯式資料庫的主機。 |
options.port | number |
|
關聯式資料庫的埠。 |
options.username | string |
|
用於向資料庫驗證的使用者名稱。 |
options.password | string |
|
用於向資料庫驗證的密碼。 |
options.database | string |
|
資料庫的名稱。 |
options.dialect | string |
|
您要連線的資料庫的方言。 必須是 mysql、postgres、sqlite、db2、mariadb 或 mssql 其中之一。 |
options.dialectModule | string |
|
如果指定,則使用此方言程式庫。例如,如果您想在連線到 pg 資料庫時使用 pg.js 而不是 pg,則應在此處指定 'require("pg.js")' |
options.dialectModulePath | string |
|
如果指定,則從此路徑載入方言程式庫。例如,如果您想在連線到 pg 資料庫時使用 pg.js 而不是 pg,則應在此處指定 '/path/to/pg.js' |
options.dialectOptions | object |
|
其他選項的物件,直接傳遞到連線程式庫 |
options.storage | string |
|
僅由 sqlite 使用。預設為 ':memory:' |
options.protocol | string |
|
關聯式資料庫的協定。 |
options.define | object |
|
模型定義的預設選項。請參閱 Model.init。 |
options.query | object |
|
sequelize.query 的預設選項 |
options.schema | string |
|
要使用的結構描述 |
options.set | object |
|
sequelize.set 的預設選項 |
options.sync | object |
|
sequelize.sync 的預設選項 |
options.timezone | string |
|
將資料庫中的日期轉換為 JavaScript 日期時使用的時區。時區也用於連線到伺服器時的 SET TIMEZONE,以確保 NOW、CURRENT_TIMESTAMP 和其他時間相關函式的結果具有正確的時區。為了獲得最佳的跨平台效能,請使用 +/-HH:MM 格式。也接受 moment.js 使用的時區字串版本(例如 'America/Los_Angeles');這對於捕獲日光節約時間的變化很有用。 |
options.clientMinMessages | string | boolean |
|
(已棄用) PostgreSQL |
options.standardConformingStrings | boolean |
|
PostgreSQL 的 |
options.logging | 函式 |
|
每次 Sequelize 記錄內容時都會執行的函式。函式可能會接收多個參數,但只有第一個參數會被 |
options.benchmark | boolean |
|
將查詢執行時間(以毫秒為單位)作為第二個參數傳遞給記錄函式 (options.logging)。 |
options.omitNull | boolean |
|
一個標記,用於定義是否應將 null 值作為值傳遞給 CREATE/UPDATE SQL 查詢。 |
options.native | boolean |
|
一個標記,用於定義是否應使用原生程式庫。目前僅對 postgres 有效 |
options.ssl | boolean |
|
一個標記,用於定義連線是否應透過 SSL 連線。 |
options.replication | boolean |
|
使用讀/寫複製。若要啟用複製,請傳遞一個物件,其中包含兩個屬性:read 和 write。Write 應該是一個物件(用於處理寫入的單一伺服器),而 read 應該是一個物件陣列(用於處理讀取的數個伺服器)。每個讀/寫伺服器可以有以下屬性: |
options.pool | object |
|
sequelize 連線池配置 |
options.pool.max | number |
|
連線池中的最大連線數 |
options.pool.min | number |
|
連線池中的最小連線數 |
options.pool.idle | number |
|
連線在釋放之前可以閒置的最大時間(以毫秒為單位)。 |
options.pool.acquire | number |
|
連線池在拋出錯誤之前嘗試取得連線的最大時間(以毫秒為單位) |
options.pool.evict | number |
|
sequelize-pool 將移除閒置連線的時間間隔(以毫秒為單位)。 |
options.pool.validate | 函式 |
|
用於驗證連線的函式。呼叫時會帶入 client。預設函式會檢查 client 是否為物件,以及其狀態是否未斷線 |
options.pool.maxUses | number |
|
在為了替換而捨棄連線之前,連線可以被使用的次數, |
options.quoteIdentifiers | boolean |
|
設定為 |
options.transactionType | string |
|
設定預設的交易類型。請參閱 |
options.isolationLevel | string |
|
設定預設的交易隔離級別。請參閱 |
options.retry | object |
|
一組標記,用於控制何時自動重試查詢。接受 |
options.retry.match | 陣列 |
|
僅在錯誤符合其中一個字串時重試查詢。 |
options.retry.max | number |
|
自動重試失敗查詢的次數。設定為 0 可停用對 SQL_BUSY 錯誤的重試。 |
options.typeValidation | boolean |
|
在插入和更新時執行內建的類型驗證器,並使用 where 子句進行選擇,例如驗證傳遞給整數字段的參數是否為類似整數。 |
options.operatorsAliases | object |
|
基於字串的運算子別名。傳遞物件以限制別名運算子的集合。 |
options.hooks | object |
|
一個全域 hook 函式的物件,這些函式會在特定生命週期事件之前和之後呼叫。全域 hook 將在為相同事件定義的任何模型特定 hook 之後執行(請參閱 |
options.minifyAliases | boolean |
|
一個標記,用於定義是否應縮減別名(主要用於避免 Postgres 別名字元數限制為 64) |
options.logQueryParameters | boolean |
|
一個標記,用於定義是否在記錄中顯示繫結參數。 |
範例
// without password / with blank password
const sequelize = new Sequelize('database', 'username', null, {
dialect: 'mysql'
})
// with password and options
const sequelize = new Sequelize('my_database', 'john', 'doe', {
dialect: 'postgres'
})
// with database, username, and password in the options object
const sequelize = new Sequelize({ database, username, password, dialect: 'mssql' });
// with uri
const sequelize = new Sequelize('mysql://127.0.0.1:3306/database', {})
// option examples
const sequelize = new Sequelize('database', 'username', 'password', {
// the sql dialect of the database
// currently supported: 'mysql', 'sqlite', 'postgres', 'mssql'
dialect: 'mysql',
// custom host; default: localhost
host: 'my.server.tld',
// for postgres, you can also specify an absolute path to a directory
// containing a UNIX socket to connect over
// host: '/sockets/psql_sockets'.
// custom port; default: dialect default
port: 12345,
// custom protocol; default: 'tcp'
// postgres only, useful for Heroku
protocol: null,
// disable logging or provide a custom logging function; default: console.log
logging: false,
// you can also pass any dialect options to the underlying dialect library
// - default is empty
// - currently supported: 'mysql', 'postgres', 'mssql'
dialectOptions: {
socketPath: '/Applications/MAMP/tmp/mysql/mysql.sock',
supportBigNumbers: true,
bigNumberStrings: true
},
// the storage engine for sqlite
// - default ':memory:'
storage: 'path/to/database.sqlite',
// disable inserting undefined values as NULL
// - default: false
omitNull: true,
// a flag for using a native library or not.
// in the case of 'pg' -- set this to true will allow SSL support
// - default: false
native: true,
// A flag that defines if connection should be over ssl or not
// - default: undefined
ssl: true,
// Specify options, which are used when sequelize.define is called.
// The following example:
// define: { timestamps: false }
// is basically the same as:
// Model.init(attributes, { timestamps: false });
// sequelize.define(name, attributes, { timestamps: false });
// so defining the timestamps for each model will be not necessary
define: {
underscored: false,
freezeTableName: false,
charset: 'utf8',
dialectOptions: {
collate: 'utf8_general_ci'
},
timestamps: true
},
// similar for sync: you can define this to always force sync for models
sync: { force: true },
// pool configuration used to pool database connections
pool: {
max: 5,
idle: 30000,
acquire: 60000,
},
// isolation level of each transaction
// defaults to dialect default
isolationLevel: Transaction.ISOLATION_LEVELS.REPEATABLE_READ
})
公開成員
公開方法
公開 非同步 authenticate(options: 物件): Promise 來源
透過嘗試驗證來測試連線。它會執行 SELECT 1+1 AS result
查詢。
參數
名稱 | 型別 | 屬性 | 描述 |
options | object |
|
查詢選項 |
公開 close(): Promise 來源
關閉此 sequelize 實例使用的所有連線,並釋放所有引用,以便可以垃圾回收該實例。
通常這會在處理程序結束時完成,因此只有在您建立多個實例,並且想要垃圾收集其中一些實例時,才需要呼叫此方法。
公開 非同步 createSchema(schema: 字串, options: 物件): Promise 來源
建立新的資料庫結構描述。
注意:這是postgres 意義上的 schema,而不是資料庫資料表。在 mysql 和 sqlite 中,此命令不會執行任何動作。
請參閱
公開 define(modelName: 字串, attributes: 物件, options: 物件): Model 來源
定義一個新的模型,表示資料庫中的一個表格。
資料表欄由作為第二個參數給定的物件定義。物件的每個鍵代表一個欄位
參數
名稱 | 型別 | 屬性 | 描述 |
modelName | string | 模型的名稱。模型將以這個名稱儲存在 |
|
attributes | object | 一個物件,其中每個屬性都是資料表的欄。請參閱 Model.init |
|
options | object |
|
這些選項會與提供給 Sequelize 建構函式的預設 define 選項合併,並傳遞給 Model.init() |
範例
sequelize.define('modelName', {
columnA: {
type: Sequelize.BOOLEAN,
validate: {
is: ["[a-z]",'i'], // will only allow letters
max: 23, // only allow values <= 23
isIn: {
args: [['en', 'zh']],
msg: "Must be English or Chinese"
}
},
field: 'column_a'
},
columnB: Sequelize.STRING,
columnC: 'MY VERY OWN COLUMN TYPE'
});
sequelize.models.modelName // The model will now be available in models under the name given to define
請參閱
- 關於 `options` 和 `attributes` 物件的更完整規格,請參閱 Model.init。
- 模型基礎指南
公開 非同步 drop(options: 物件): Promise 來源
捨棄透過此 sequelize 實例定義的所有資料表。這是透過在每個模型上呼叫 Model.drop 來完成的。
請參閱
- 關於選項,請參閱 Model.drop
公開 非同步 dropAllSchemas(options: 物件): Promise 來源
刪除所有結構描述。
注意:這是postgres 意義上的 schema,而不是資料庫資料表。在 mysql 和 sqlite 中,這相當於捨棄所有資料表。
公開 非同步 dropSchema(schema: 字串, options: 物件): Promise 來源
刪除單一結構描述
注意:這是postgres 意義上的 schema,而不是資料庫資料表。在 mysql 和 sqlite 中,這會捨棄與 schema 名稱相符的資料表
public isDefined(modelName: string): boolean 原始碼
檢查是否已定義具有給定名稱的模型
參數
名稱 | 型別 | 屬性 | 描述 |
modelName | string | 使用 Sequelize.define 定義的模型名稱 |
public model(modelName: string): Model 原始碼
擷取已定義的模型
參數
名稱 | 型別 | 屬性 | 描述 |
modelName | string | 使用 Sequelize.define 定義的模型名稱 |
拋出
* |
如果模型未定義(也就是說,如果 sequelize#isDefined 返回 false),將拋出錯誤 |
public async query(sql: string, options: object): Promise 原始碼
在資料庫上執行查詢,可選擇繞過所有 Sequelize 的優點。
預設情況下,此函數將返回兩個參數:結果陣列和包含受影響行數等的元數據物件。
如果您正在執行不需要元數據的查詢類型,例如 SELECT
查詢,您可以傳入查詢類型,使 sequelize 格式化結果
const [results, metadata] = await sequelize.query('SELECT...'); // Raw query - use array destructuring
const results = await sequelize.query('SELECT...', { type: sequelize.QueryTypes.SELECT }); // SELECT query - no destructuring
參數
名稱 | 型別 | 屬性 | 描述 |
sql | string | ||
options | object |
|
查詢選項。 |
options.raw | boolean |
|
如果為 true,sequelize 將不會嘗試格式化查詢結果,或從結果建立模型的實例 |
options.transaction | 交易 |
|
應在其中執行查詢的交易 |
options.type | QueryTypes |
|
您正在執行的查詢類型。查詢類型會影響結果在傳回之前如何格式化。類型為字串,但提供 |
options.nest | boolean |
|
如果為 true,則使用 dottie.js 將具有 |
options.plain | boolean |
|
將查詢類型設定為 |
options.replacements | object | Array |
|
格式為 |
options.bind | object | Array |
|
格式為 |
options.useMaster | boolean |
|
強制查詢使用寫入池,無論查詢類型為何。 |
options.logging | 函式 |
|
執行查詢時執行以記錄 SQL 的函數。 |
options.instance | Model |
|
要用於建立查詢結果的 Sequelize 模型實例 |
options.model | typeof Model |
|
用於建立傳回的模型實例的 Sequelize 模型 |
options.retry | object |
|
一組標記,用於控制何時自動重試查詢。接受 |
options.retry.match | 陣列 |
|
僅在錯誤符合其中一個字串時重試查詢。 |
options.retry.max | Integer |
|
自動重試失敗查詢的次數。 |
options.searchPath | string |
|
用於指定綱要 search_path 的可選參數 (僅限 Postgres) |
options.supportsSearchPath | boolean |
|
如果為 false,則不要在查詢前面加上 search_path (僅限 Postgres) |
options.mapToModel | boolean |
|
如果存在 |
options.fieldMap | object |
|
對於 |
options.rawErrors | boolean |
|
設定為 |
請參閱
- 有關實例選項的詳細資訊,請參閱 Model.build。
public async set(variables: object, options: object): Promise 原始碼
執行一個查詢,該查詢將設定環境或使用者變數。變數是每個連線設定的,因此此函數需要交易。僅適用於 MySQL 或 MariaDB。
public async showAllSchemas(options: object): Promise 原始碼
顯示所有已定義的結構描述
注意:這是 Postgres 意義上的綱要,而不是資料庫表。在 MySQL 和 SQLite 中,這將顯示所有表。
public async sync(options: object): Promise 原始碼
將所有已定義的模型同步到資料庫。
參數
名稱 | 型別 | 屬性 | 描述 |
options | object |
|
同步選項 |
options.force | boolean |
|
如果 force 為 true,每個模型會在嘗試建立自己的表之前執行 |
options.match | RegExp |
|
在同步之前將正規表示式與資料庫名稱進行比對,這是用於在測試中使用 force: true 但不使用實際程式碼時的安全檢查 |
options.logging | 布林值 | 函式 |
|
一個記錄 sql 查詢的函式,或者不記錄時為 false |
options.schema | string |
|
應該在其中建立表的綱要。這可以在 sequelize.define 中針對每個表進行覆寫 |
options.searchPath | string |
|
用於指定綱要 search_path 的可選參數 (僅限 Postgres) |
options.hooks | boolean |
|
如果 hooks 為 true,則會呼叫 beforeSync、afterSync、beforeBulkSync、afterBulkSync hook |
options.alter | boolean | object |
|
變更表以符合模型。提供物件以進行其他設定。不建議用於生產環境。如果沒有進一步設定,則會刪除模型中已移除或變更類型的欄位中的資料。 |
options.alter.drop | boolean |
|
設定為 |
public async transaction(options: object, autoCallback: Function): Promise 原始碼
啟動交易。使用交易時,您應在 options 參數中傳遞交易,以便查詢在該交易下發生 @see Transaction
如果您已啟用 CLS,則該交易會自動傳遞給在回呼中執行的任何查詢
參數
名稱 | 型別 | 屬性 | 描述 |
options | object |
|
交易選項 |
options.type | string |
|
有關可能的選項,請參閱 |
options.isolationLevel | string |
|
有關可能的選項,請參閱 |
options.deferrable | string |
|
設定要延遲或立即檢查的約束。請參閱 |
options.readOnly | boolean |
|
此交易是否僅用於讀取資料。用於判斷是否允許 sequelize 使用讀取複寫伺服器。 |
options.logging | 函式 |
|
執行查詢時執行以記錄 SQL 的函數。 |
autoCallback | 函式 |
|
回呼會以交易物件呼叫,且應傳回 Promise。如果 Promise 已解決,則交易會提交;如果 Promise 遭到拒絕,則交易會回滾 |
範例
try {
const transaction = await sequelize.transaction();
const user = await User.findOne(..., { transaction });
await user.update(..., { transaction });
await transaction.commit();
} catch {
await transaction.rollback()
}
try {
await sequelize.transaction(transaction => { // Note that we pass a callback rather than awaiting the call with no arguments
const user = await User.findOne(..., {transaction});
await user.update(..., {transaction});
});
// Committed
} catch(err) {
// Rolled back
console.error(err);
}
const cls = require('cls-hooked');
const namespace = cls.createNamespace('....');
const Sequelize = require('sequelize');
Sequelize.useCLS(namespace);
// Note, that CLS is enabled for all sequelize instances, and all instances will share the same namespace