Sequelize
This is the main class, the entry point to sequelize. To use it, you just need to import sequelize:
const Sequelize = require('sequelize');
In addition to sequelize, the connection library for the dialect you want to use should also be installed in your project. You don't need to import it however, as sequelize will take care of that.
Static Method Summary
Static Public Methods | ||
public static |
An AND query |
since v2.0.0-dev3 |
public static |
Creates an object representing a call to the cast function. |
since v2.0.0-dev3 |
public static |
Creates an object which represents a column in the DB, this allows referencing another column in your query. |
since v2.0.0-dev3 |
public static |
Creates an object representing a database function. |
since v2.0.0-dev3 |
public static |
Creates an object representing nested where conditions for postgres/sqlite/mysql json data-type. |
|
public static |
Creates an object representing a literal, i.e. |
since v2.0.0-dev3 |
public static |
An OR query |
since v2.0.0-dev3 |
public static |
useCLS(ns: Object): Object Use CLS with Sequelize. |
|
public static |
A way of specifying attr = condition. |
since v2.0.0-dev3 |
Constructor Summary
Public Constructor | ||
public |
constructor(database: String, username: String, password: String, options: Object) Instantiate sequelize with name of database, username and password |
Member Summary
Public Members | ||
public |
models: {} Models are stored here under the name given to |
Method Summary
Public Methods | ||
public |
authenticate(options: *): Promise Test the connection by trying to authenticate |
|
public |
close(): Promise Close all connections used by this sequelize instance, and free all references so the instance can be garbage collected. |
|
public |
createSchema(schema: String, options: Object): Promise Create a new database schema. |
|
public |
Define a new model, representing a table in the DB. |
|
public |
drop(options: object): Promise Drop all tables defined through this sequelize instance. |
|
public |
dropAllSchemas(options: Object): Promise Drop all schemas |
|
public |
dropSchema(schema: String, options: Object): Promise Drop a single schema |
|
public |
escape(value: String): String Escape value. |
|
public |
getDialect(): String Returns the specified dialect. |
|
public |
Returns an instance of QueryInterface. |
|
public |
Imports a model defined in another file |
|
public |
isDefined(modelName: String): Boolean Checks whether a model with the given name is defined |
|
public |
Fetch a Model which is already defined |
|
public |
query(sql: String, options: Object): Promise Execute a query on the DB, with the possibility to bypass all the sequelize goodness. |
|
public |
Get the fn for random based on the dialect |
|
public |
set(variables: Object, options: Object): Promise Execute a query which would set an environment or user variable. |
|
public |
showAllSchemas(options: Object): Promise Show all defined schemas |
|
public |
sync(options: Object): Promise Sync all defined models to the DB. |
|
public |
transaction(options: Object, autoCallback: Function): Promise Start a transaction. |
|
public |
truncate(options: object): Promise Truncate all tables defined through the sequelize models. |
Static Public Methods
public static and(args: String | Object): and since v2.0.0-dev3 source
An AND query
Params:
Name | Type | Attribute | Description |
args | String | Object | Each argument will be joined by AND |
See:
public static cast(val: any, type: String): cast since v2.0.0-dev3 source
Creates an object representing a call to the cast function.
Params:
Name | Type | Attribute | Description |
val | any | The value to cast |
|
type | String | The type to cast it to |
public static col(col: String): col since v2.0.0-dev3 source
Creates an object which represents a column in the DB, this allows referencing another column in your query. This is often useful in conjunction with sequelize.fn
, since raw string arguments to fn will be escaped.
Params:
Name | Type | Attribute | Description |
col | String | The name of the column |
See:
- Sequelize#fn
public static fn(fn: String, args: any): fn since v2.0.0-dev3 source
Creates an object representing a database function. This can be used in search queries, both in where and order parts, and as default values in column definitions.
If you want to refer to columns in your function, you should use sequelize.col
, so that the columns are properly interpreted as columns and not a strings.
Convert a user's username to upper case
instance.updateAttributes({
username: self.sequelize.fn('upper', self.sequelize.col('username'))
})
Params:
Name | Type | Attribute | Description |
fn | String | The function you want to call |
|
args | any | All further arguments will be passed as arguments to the function |
Example:
instance.updateAttributes({
username: self.sequelize.fn('upper', self.sequelize.col('username'))
})
public static json(conditions: String | Object, value: String | Number | Boolean): json source
Creates an object representing nested where conditions for postgres/sqlite/mysql json data-type.
Params:
Name | Type | Attribute | Description |
conditions | String | Object | A hash containing strings/numbers or other nested hash, a string using dot notation or a string using postgres/sqlite/mysql json syntax. |
|
value | String | Number | Boolean |
|
An optional value to compare against. Produces a string of the form "<json path> = '<value>'". |
See:
- Model#findAll
public static literal(val: any): literal since v2.0.0-dev3 source
Creates an object representing a literal, i.e. something that will not be escaped.
Params:
Name | Type | Attribute | Description |
val | any |
public static or(args: String | Object): or since v2.0.0-dev3 source
An OR query
Params:
Name | Type | Attribute | Description |
args | String | Object | Each argument will be joined by OR |
See:
public static useCLS(ns: Object): Object source
Use CLS with Sequelize.
CLS namespace provided is stored as Sequelize._cls
and bluebird Promise is patched to use the namespace, using cls-bluebird
module.
Params:
Name | Type | Attribute | Description |
ns | Object | CLS namespace |
Return:
Object | Sequelize constructor |
public static where(attr: Object, comparator: String | Op, logic: String | Object): * since v2.0.0-dev3 source
A way of specifying attr = condition.
The attr can either be an object taken from Model.rawAttributes
(for example Model.rawAttributes.id
or Model.rawAttributes.name
). The
attribute should be defined in your model definition. The attribute can also be an object from one of the sequelize utility functions (sequelize.fn
, sequelize.col
etc.)
For string attributes, use the regular { where: { attr: something }}
syntax. If you don't want your string to be escaped, use sequelize.literal
.
Params:
Name | Type | Attribute | Description |
attr | Object | The attribute, which can be either an attribute object from |
|
comparator | String | Op |
|
|
logic | String | Object | The condition. Can be both a simply type, or a further condition ( |
Return:
* |
See:
Public Constructors
public constructor(database: String, username: String, password: String, options: Object) source
Instantiate sequelize with name of database, username and password
Example usage
// without password and options
const sequelize = new Sequelize('database', 'username')
// without options
const sequelize = new Sequelize('database', 'username', 'password')
// without password / with blank password
const sequelize = new Sequelize('database', 'username', null, {})
// with password and options
const sequelize = new Sequelize('my_database', 'john', 'doe', {})
// with database, username, and password in the options object
const sequelize = new Sequelize({ database, username, password });
// with uri
const sequelize = new Sequelize('mysql://localhost:3306/database', {})
Params:
Name | Type | Attribute | Description |
database | String |
|
The name of the database |
username | String |
|
The username which is used to authenticate against the database. |
password | String |
|
The password which is used to authenticate against the database. Supports SQLCipher encryption for SQLite. |
options | Object |
|
An object with options. |
options.host | String |
|
The host of the relational database. |
options.port | Integer |
|
The port of the relational database. |
options.username | String |
|
The username which is used to authenticate against the database. |
options.password | String |
|
The password which is used to authenticate against the database. |
options.database | String |
|
The name of the database |
options.dialect | String |
|
The dialect of the database you are connecting to. One of mysql, postgres, sqlite and mssql. |
options.dialectModulePath | String |
|
If specified, load the dialect library from this path. For example, if you want to use pg.js instead of pg when connecting to a pg database, you should specify 'pg.js' here |
options.dialectOptions | Object |
|
An object of additional options, which are passed directly to the connection library |
options.storage | String |
|
Only used by sqlite. Defaults to ':memory:' |
options.protocol | String |
|
The protocol of the relational database. |
options.define | Object |
|
Default options for model definitions. See sequelize.define for options |
options.query | Object |
|
Default options for sequelize.query |
options.set | Object |
|
Default options for sequelize.set |
options.sync | Object |
|
Default options for sequelize.sync |
options.timezone | string |
|
The timezone used when converting a date from the database into a JavaScript date. The timezone is also used to SET TIMEZONE when connecting to the server, to ensure that the result of NOW, CURRENT_TIMESTAMP and other time related functions have in the right timezone. For best cross platform performance use the format +/-HH:MM. Will also accept string versions of timezones used by moment.js (e.g. 'America/Los_Angeles'); this is useful to capture daylight savings time changes. |
options.standardConformingStrings | boolean |
|
The PostgreSQL |
options.logging | Function |
|
A function that gets executed every time Sequelize would log something. |
options.benchmark | Boolean |
|
Pass query execution time in milliseconds as second argument to logging function (options.logging). |
options.omitNull | Boolean |
|
A flag that defines if null values should be passed to SQL queries or not. |
options.native | Boolean |
|
A flag that defines if native library shall be used or not. Currently only has an effect for postgres |
options.replication | Boolean |
|
Use read / write replication. To enable replication, pass an object, with two properties, read and write. Write should be an object (a single server for handling writes), and read an array of object (several servers to handle reads). Each read/write server can have the following properties: |
options.pool | Object |
|
sequelize connection pool configuration |
options.pool.max | Integer |
|
Maximum number of connection in pool |
options.pool.min | Integer |
|
Minimum number of connection in pool |
options.pool.idle | Integer |
|
The maximum time, in milliseconds, that a connection can be idle before being released. Use with combination of evict for proper working, for more details read https://github.com/coopernurse/node-pool/issues/178#issuecomment-327110870 |
options.pool.acquire | Integer |
|
The maximum time, in milliseconds, that pool will try to get connection before throwing error |
options.pool.evict | Integer |
|
The time interval, in milliseconds, for evicting stale connections. Set it to 0 to disable this feature. |
options.pool.handleDisconnects | Boolean |
|
Controls if pool should handle connection disconnect automatically without throwing errors |
options.pool.validate | Function |
|
A function that validates a connection. Called with client. The default function checks that client is an object, and that its state is not disconnected |
options.quoteIdentifiers | Boolean |
|
Set to |
options.transactionType | String |
|
Set the default transaction type. See |
options.isolationLevel | String |
|
Set the default transaction isolation level. See |
options.retry | Object |
|
Set of flags that control when a query is automatically retried. |
options.retry.match | Array |
|
Only retry a query if the error matches one of these strings. |
options.retry.max | Integer |
|
How many times a failing query is automatically retried. Set to 0 to disable retrying on SQL_BUSY error. |
options.typeValidation | Boolean |
|
Run built in type validators on insert and update, e.g. validate that arguments passed to integer fields are integer-like. |
options.operatorsAliases | Object | Boolean |
|
String based operator alias, default value is true which will enable all operators alias. Pass object to limit set of aliased operators or false to disable completely. |
Public Members
Public Methods
public authenticate(options: *): Promise source
Test the connection by trying to authenticate
Params:
Name | Type | Attribute | Description |
options | * |
Return:
Promise |
public close(): Promise source
Close all connections used by this sequelize instance, and free all references so the instance can be garbage collected.
Normally this is done on process exit, so you only need to call this method if you are creating multiple instances, and want to garbage collect some of them.
Return:
Promise |
public createSchema(schema: String, options: Object): Promise source
Create a new database schema.
Note, that this is a schema in the postgres sense of the word, not a database table. In mysql and sqlite, this command will do nothing.
Params:
Name | Type | Attribute | Description |
schema | String | Name of the schema |
|
options | Object |
|
|
options.logging | Boolean | function | A function that logs sql queries, or false for no logging |
Return:
Promise |
See:
public define(modelName: String, attributes: Object, options: Object): Model source
Define a new model, representing a table in the DB.
The table columns are defined by the object that is given as the second argument. Each key of the object represents a column
Params:
Name | Type | Attribute | Description |
modelName | String | The name of the model. The model will be stored in |
|
attributes | Object | An object, where each attribute is a column of the table. See Model.init |
|
options | Object |
|
These options are merged with the default define options provided to the Sequelize constructor and passed to Model.init() |
Example:
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'
// Other attributes here
},
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
See:
- Model.init for a more comprehensive specification of the `options` and `attributes` objects.
- The manual section about defining models
- DataTypes For a list of possible data types
public drop(options: object): Promise source
Drop all tables defined through this sequelize instance. This is done by calling Model.drop on each model
Params:
Name | Type | Attribute | Description |
options | object | The options passed to each call to Model.drop |
|
options.logging | Boolean | function | A function that logs sql queries, or false for no logging |
Return:
Promise |
See:
- Model.drop for options
public dropAllSchemas(options: Object): Promise source
Drop all schemas
Note,that this is a schema in the postgres sense of the word, not a database table. In mysql and sqlite, this is the equivalent of drop all tables.
Params:
Name | Type | Attribute | Description |
options | Object |
|
|
options.logging | Boolean | function | A function that logs sql queries, or false for no logging |
Return:
Promise |
public dropSchema(schema: String, options: Object): Promise source
Drop a single schema
Note, that this is a schema in the postgres sense of the word, not a database table. In mysql and sqlite, this drop a table matching the schema name
Params:
Name | Type | Attribute | Description |
schema | String | Name of the schema |
|
options | Object |
|
|
options.logging | Boolean | function | A function that logs sql queries, or false for no logging |
Return:
Promise |
public escape(value: String): String source
Escape value.
Params:
Name | Type | Attribute | Description |
value | String |
Return:
String |
public getDialect(): String source
Returns the specified dialect.
Return:
String | The specified dialect. |
public import(path: String): Model source
Imports a model defined in another file
Imported models are cached, so multiple calls to import with the same path will not load the file multiple times
See https://github.com/sequelize/express-example for a short example of how to define your models in separate files so that they can be imported by sequelize.import
Params:
Name | Type | Attribute | Description |
path | String | The path to the file that holds the model you want to import. If the part is relative, it will be resolved relatively to the calling file |
public isDefined(modelName: String): Boolean source
Checks whether a model with the given name is defined
Params:
Name | Type | Attribute | Description |
modelName | String | The name of a model defined with Sequelize.define |
Return:
Boolean |
public model(modelName: String): Model source
Fetch a Model which is already defined
Params:
Name | Type | Attribute | Description |
modelName | String | The name of a model defined with Sequelize.define |
Throw:
* |
Will throw an error if the model is not defined (that is, if sequelize#isDefined returns false) |
public query(sql: String, options: Object): Promise source
Execute a query on the DB, with the possibility to bypass all the sequelize goodness.
By default, the function will return two arguments: an array of results, and a metadata object, containing number of affected rows etc. Use .spread
to access the results.
If you are running a type of query where you don't need the metadata, for example a SELECT
query, you can pass in a query type to make sequelize format the results:
sequelize.query('SELECT...').spread((results, metadata) => {
// Raw query - use spread
});
sequelize.query('SELECT...', { type: sequelize.QueryTypes.SELECT }).then(results => {
// SELECT query - use then
})
Params:
Name | Type | Attribute | Description |
sql | String | ||
options | Object |
|
Query options. |
options.raw | Boolean |
|
If true, sequelize will not try to format the results of the query, or build an instance of a model from the result |
options.transaction | Transaction |
|
The transaction that the query should be executed under |
options.type | QueryTypes |
|
The type of query you are executing. The query type affects how results are formatted before they are passed back. The type is a string, but |
options.nest | Boolean |
|
If true, transforms objects with |
options.plain | Boolean |
|
Sets the query type to |
options.replacements | Object | Array |
|
Either an object of named parameter replacements in the format |
options.bind | Object | Array |
|
Either an object of named bind parameter in the format |
options.useMaster | Boolean |
|
Force the query to use the write pool, regardless of the query type. |
options.logging | Function |
|
A function that gets executed while running the query to log the sql. |
options.instance | new Model() |
|
A sequelize instance used to build the return instance |
options.model | Model |
|
A sequelize model used to build the returned model instances (used to be called callee) |
options.retry | Object |
|
Set of flags that control when a query is automatically retried. |
options.retry.match | Array |
|
Only retry a query if the error matches one of these strings. |
options.retry.max | Integer |
|
How many times a failing query is automatically retried. |
options.searchPath | String |
|
An optional parameter to specify the schema search_path (Postgres only) |
options.supportsSearchPath | Boolean |
|
If false do not prepend the query with the search_path (Postgres only) |
options.mapToModel | Boolean |
|
Map returned fields to model's fields if |
options.fieldMap | Object |
|
Map returned fields to arbitrary names for |
Return:
Promise |
See:
- Model.build for more information about instance option.
public set(variables: Object, options: Object): Promise source
Execute a query which would set an environment or user variable. The variables are set per connection, so this function needs a transaction. Only works for MySQL.
Params:
Name | Type | Attribute | Description |
variables | Object | Object with multiple variables. |
|
options | Object | Query options. |
|
options.transaction | Transaction | The transaction that the query should be executed under |
Return:
Promise |
public showAllSchemas(options: Object): Promise source
Show all defined schemas
Note, that this is a schema in the postgres sense of the word, not a database table. In mysql and sqlite, this will show all tables.
Params:
Name | Type | Attribute | Description |
options | Object |
|
|
options.logging | Boolean | function | A function that logs sql queries, or false for no logging |
Return:
Promise |
public sync(options: Object): Promise source
Sync all defined models to the DB.
Params:
Name | Type | Attribute | Description |
options | Object |
|
|
options.force | Boolean |
|
If force is true, each Model will run |
options.match | RegExp |
|
Match a regex against the database name before syncing, a safety check for cases where force: true is used in tests but not live code |
options.logging | Boolean | function |
|
A function that logs sql queries, or false for no logging |
options.schema | String |
|
The schema that the tables should be created in. This can be overriden for each table in sequelize.define |
options.searchPath | String |
|
An optional parameter to specify the schema search_path (Postgres only) |
options.hooks | Boolean |
|
If hooks is true then beforeSync, afterSync, beforeBulkSync, afterBulkSync hooks will be called |
options.alter | Boolean |
|
Alters tables to fit models. Not recommended for production use. Deletes data in columns that were removed or had their type changed in the model. |
Return:
Promise |
public transaction(options: Object, autoCallback: Function): Promise source
Start a transaction. When using transactions, you should pass the transaction in the options argument in order for the query to happen under that transaction
sequelize.transaction().then(transaction => {
return User.findOne(..., {transaction})
.then(user => user.updateAttributes(..., {transaction}))
.then(() => transaction.commit())
.catch(() => transaction.rollback());
})
A syntax for automatically committing or rolling back based on the promise chain resolution is also supported:
sequelize.transaction(transaction => { // Note that we use a callback rather than a promise.then()
return User.findOne(..., {transaction})
.then(user => user.updateAttributes(..., {transaction}))
}).then(() => {
// Committed
}).catch(err => {
// Rolled back
console.error(err);
});
If you have CLS enabled, the transaction will automatically be passed to any query that runs within the callback. To enable CLS, add it do your project, create a namespace and set it on the sequelize constructor:
const cls = require('continuation-local-storage');
const ns = cls.createNamespace('....');
const Sequelize = require('sequelize');
Sequelize.useCLS(ns);
Note, that CLS is enabled for all sequelize instances, and all instances will share the same namespace
Params:
Name | Type | Attribute | Description |
options | Object |
|
|
options.autocommit | Boolean |
|
|
options.type | String |
|
See |
options.isolationLevel | String |
|
See |
options.logging | Function |
|
A function that gets executed while running the query to log the sql. |
autoCallback | Function |
|
The callback is called with the transaction object, and should return a promise. If the promise is resolved, the transaction commits; if the promise rejects, the transaction rolls back |
Return:
Promise |
See:
public truncate(options: object): Promise source
Truncate all tables defined through the sequelize models. This is done by calling Model.truncate() on each model.
Params:
Name | Type | Attribute | Description |
options | object |
|
The options passed to Model.destroy in addition to truncate |
options.transaction | Boolean | function |
|
|
options.logging | Boolean | function |
|
A function that logs sql queries, or false for no logging |
Return:
Promise |
See:
- Model.truncate for more information