This is the main class, the entry point to sequelize.
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 | Use CLS with Sequelize. | |
public static | A way of specifying attr = condition. | since v2.0.0-dev3 |
Public Constructor | ||
---|---|---|
public | constructor(database: string, username: string, password: string, options: Object) Instantiate sequelize with name of database, username and password. |
Public Members | ||
---|---|---|
public | models: {} Models are stored here under the name given to |
Public Methods | ||
---|---|---|
public | authenticate(options: Object): Promise Test the connection by trying to authenticate. | |
public | 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 database. | |
public | 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. | |
public | Returns the database name. | |
public | getDialect(): string Returns the specified dialect. | |
public | Returns an instance of QueryInterface. | |
public | Imports a model defined in another file. | |
public | Checks whether a model with the given name is defined | |
public | Fetch a Model which is already defined | |
public | Execute a query on the DB, optionally bypassing all the Sequelize goodness. | |
public | Get the fn for random based on the dialect | |
public | Execute a query which would set an environment or user variable. | |
public | showAllSchemas(options: Object): Promise Show all defined schemas | |
public | Sync all defined models to the DB. | |
public | transaction(options: Object, autoCallback: Function): Promise Start a transaction. | |
public | Truncate all tables defined through the sequelize models. |
An AND query
and |
Creates an object representing a call to the cast function.
Name | Type | Attribute | Description |
---|---|---|---|
val | any |
The value to cast | |
type | string |
The type to cast it to |
cast |
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.
Name | Type | Attribute | Description |
---|---|---|---|
col | string |
The name of the column |
col |
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.
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 |
fn |
instance.update({
username: sequelize.fn('upper', sequelize.col('username'))
});
Creates an object representing nested where conditions for postgres/sqlite/mysql json data-type.
Name | Type | Attribute | Description |
---|---|---|---|
conditionsOrPath | 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>'". |
json |
Creates an object representing a literal, i.e. something that will not be escaped.
Name | Type | Attribute | Description |
---|---|---|---|
val | any |
literal value |
literal |
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.
Name | Type | Attribute | Description |
---|---|---|---|
ns | Object |
CLS namespace |
Object |
Sequelize constructor |
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
.
Name | Type | Attribute | Description |
---|---|---|---|
attr | Object |
The attribute, which can be either an attribute object from | |
comparator | Symbol |
|
operator |
logic | string | Object |
The condition. Can be both a simply type, or a further condition ( |
* |
Instantiate sequelize with name of database, username and password.
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 | number |
|
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.dialectModule | string |
|
If specified, use this dialect library. For example, if you want to use pg.js instead of pg when connecting to a pg database, you should specify 'require("pg.js")' here |
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 '/path/to/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 Model.init. |
options.query | Object |
|
Default options for sequelize.query |
options.schema | string |
|
A schema to use |
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.clientMinMessages | string | boolean |
|
The PostgreSQL |
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 | number |
|
Maximum number of connection in pool |
options.pool.min | number |
|
Minimum number of connection in pool |
options.pool.idle | number |
|
The maximum time, in milliseconds, that a connection can be idle before being released. |
options.pool.acquire | number |
|
The maximum time, in milliseconds, that pool will try to get connection before throwing error |
options.pool.evict | number |
|
The time interval, in milliseconds, after which sequelize-pool will remove idle connections. |
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 | number |
|
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, and select with where clause, e.g. validate that arguments passed to integer fields are integer-like. |
options.operatorsAliases | Object |
|
String based operator alias. Pass object to limit set of aliased operators. |
options.hooks | Object |
|
An object of global hook functions that are called before and after certain lifecycle events. Global hooks will run after any model-specific hooks defined for the same event (See |
options.minifyAliases | boolean |
|
A flag that defines if aliases should be minified (mostly useful to avoid Postgres alias character limit of 64) |
options.logQueryParameters | boolean |
|
A flag that defines if show bind patameters in log. |
// 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://localhost: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,
// 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
})
Models are stored here under the name given to sequelize.define
Test the connection by trying to authenticate. It runs SELECT 1+1 AS result
query.
Name | Type | Attribute | Description |
---|---|---|---|
options | Object |
|
query options |
Promise |
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.
Promise |
Create a new database schema.
Note: this is a schema in the postgres sense of the word, not a database table. In mysql and sqlite, this command will do nothing.
Promise |
Define a new model, representing a table in the database.
The table columns are defined by the object that is given as the second argument. Each key of the object represents a column
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() |
Model |
Newly defined model |
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
Drop all tables defined through this sequelize instance. This is done by calling Model.drop on each model.
Promise |
Drop all schemas.
Note: 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.
Promise |
Drop a single schema
Note: 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
Promise |
Escape value.
Name | Type | Attribute | Description |
---|---|---|---|
value | string |
string value to escape |
string |
Returns the database name.
string |
The database name. |
Returns the specified dialect.
string |
The specified dialect. |
Returns an instance of QueryInterface.
QueryInterface |
An instance (singleton) of QueryInterface. |
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.
Name | Type | Attribute | Description |
---|---|---|---|
importPath | 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 |
Model |
Imported model, returned from cache if was already imported |
Checks whether a model with the given name is defined
Name | Type | Attribute | Description |
---|---|---|---|
modelName | string |
The name of a model defined with Sequelize.define |
boolean |
Returns true if model is already defined, otherwise false |
Fetch a Model which is already defined
Name | Type | Attribute | Description |
---|---|---|---|
modelName | string |
The name of a model defined with Sequelize.define |
Model |
Specified model |
* |
Will throw an error if the model is not defined (that is, if sequelize#isDefined returns false) |
Execute a query on the DB, optionally bypassing 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.
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...').then(([results, metadata]) => {
// Raw query - use then plus array spread
});
sequelize.query('SELECT...', { type: sequelize.QueryTypes.SELECT }).then(results => {
// SELECT query - use then
})
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 |
Promise |
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.
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 |
Promise |
Show all defined schemas
Note: this is a schema in the postgres sense of the word, not a database table. In mysql and sqlite, this will show all tables.
Promise |
Sync all defined models to the DB.
Name | Type | Attribute | Description |
---|---|---|---|
options | Object |
|
sync options |
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 overridden 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. |
Promise |
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 @see Transaction
If you have CLS enabled, the transaction will automatically be passed to any query that runs within the callback
Name | Type | Attribute | Description |
---|---|---|---|
options | Object |
|
Transaction options |
options.type | string |
|
See |
options.isolationLevel | string |
|
See |
options.deferrable | string |
|
Sets the constraints to be deferred or immediately checked. 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 |
Promise |
sequelize.transaction().then(transaction => {
return User.findOne(..., {transaction})
.then(user => user.update(..., {transaction}))
.then(() => transaction.commit())
.catch(() => transaction.rollback());
})
sequelize.transaction(transaction => { // Note that we use a callback rather than a promise.then()
return User.findOne(..., {transaction})
.then(user => user.update(..., {transaction}))
}).then(() => {
// 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
Truncate all tables defined through the sequelize models. This is done by calling Model.truncate()
on each model.
Promise |
Copyright © 2014–present Sequelize contributors
Licensed under the MIT License.
https://sequelize.org/master/class/lib/sequelize.js~Sequelize.html