Private
#databasePrivate
#databasePrivate
#isPrivate
Readonly
#modelsPrivate
Readonly
#transactionA reference to Sequelize constructor from sequelize. Useful for accessing DataTypes, Errors etc.
A hook that is run at the end of Sequelize#sync
A hook that is run after a connection is created
A hook that is run at the end of Sequelize#define and Model.init
A hook that is run after a connection is disconnected
A hook that is run after a find (select) query
A hook that is run after a connection to the pool
Optional
options: AcquireConnectionOptionsA hook that is run at the end of Model.sync
A hook that is run at the start of Sequelize#sync
A hook that is run before a connection is created
A hook that is run at the start of Model.count
A hook that is run at the start of Sequelize#define and Model.init
A hook that is run before a connection is disconnected
A hook that is run before a find (select) query
A hook that is run before a find (select) query, after any { include: {all: ...} }
options are expanded
use beforeFind
instead
A hook that is run before a find (select) query, after all option have been normalized
use beforeFind
instead
A hook that is run before a connection to the pool
Optional
options: AcquireConnectionOptionsA hook that is run at the start of Model.sync
Readonly
dialectReadonly
modelsReadonly
optionsReadonly
poolReadonly
rawThe options that were used to create this Sequelize instance. These are an unmodified copy of the options passed to the constructor. They are not normalized or validated.
Mostly available for cloning the Sequelize instance. For other uses, we recommend using options instead.
Static
addStatic
afterA hook that is run at the end of the creation of a Sequelize instance.
Static
beforeA hook that is run at the beginning of the creation of a Sequelize instance.
Static
hasStatic
hasStatic
removeStatic
runStatic
hooksStatic
versionReturns the installed version of Sequelize
Private
#initializeTest the connection by trying to authenticate
Optional
options: QueryOptionsQuery Options for authentication
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.
Alias of AbstractQueryInterface#createSchema
Name of the schema
Optional
options: CreateSchemaOptionsDefine a new model, representing a table in the DB.
The table columns are defined by the hash that is given as the second argument. Each attribute of the hash represents a column. A short table definition might look like this:
class MyModel extends Model {}
MyModel.init({
columnA: {
type: DataTypes.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: DataTypes.STRING,
columnC: 'MY VERY OWN COLUMN TYPE'
}, { sequelize })
sequelize.models.modelName // The model will now be available in models under the name given to define
As shown above, column definitions can be either strings, a reference to one of the datatypes that are predefined on the Sequelize constructor, or an object that allows you to specify both the type of the column, and other attributes such as default values, foreign key constraints and custom setters and getters.
For a list of possible data types, see https://sequelize.org/docs/v7/other-topics/other-data-types
For more about getters and setters, see https://sequelize.org/docs/v7/core-concepts/getters-setters-virtuals/
For more about instance and class methods, see https://sequelize.org/docs/v7/core-concepts/model-basics/#taking-advantage-of-models-being-classes
For more about validation, see https://sequelize.org/docs/v7/core-concepts/validations-and-constraints/
The name of the model. The model will be stored in sequelize.models
under this name
Optional
attributes: ModelAttributes<M, TAttributes>An object, where each attribute is a column of the table. Each column can be either a DataType, a string or a type-description object, with the properties described below:
Optional
options: ModelOptions<M>These options are merged with the default define options provided to the Sequelize constructor
A slower alternative to truncate that uses DELETE FROM instead of TRUNCATE, but which works with foreign key constraints in dialects that don't support TRUNCATE CASCADE (postgres), or temporarily disabling foreign key constraints (mysql, mariadb, sqlite).
Optional
options: Omit<DestroyOptions<any>, "truncate" | "where" | "limit">Drop all tables defined through this sequelize instance. This is done by calling Model.drop on each model
Optional
options: DropOptionsThe options passed to each call to Model.drop
Optional
options: QiDropAllSchemasOptionsAlias of AbstractQueryInterface#dropSchema
Optional
options: QueryRawOptionsEscape value to be used in raw SQL.
If you are using this to use the value in a literal, consider using sql instead, which automatically escapes interpolated values.
The value to escape
Optional
options: EscapeOptionsOptional
options: QueryRawOptionsReturns the transaction that is associated to the current asynchronous operation. This method returns undefined if no transaction is active in the current asynchronous operation, or if the Sequelize "disableClsTransactions" option is true.
Throws if the database version hasn't been loaded yet. It is automatically loaded the first time Sequelize connects to your database.
You can use Sequelize#authenticate to cause a first connection.
current version of the dialect that is internally loaded
Checks whether a model with the given name is defined
The name of a model defined with Sequelize.define
use Sequelize#models instead.
Fetch a Model which is already defined
The name of a model defined with Sequelize.define
use Sequelize#models instead.
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. Use const [results, meta] = await ...
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:
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
Query options
Optional
options: QueryOptions | QueryOptionsWithType<RAW>Works like Sequelize#query, but does not inline replacements. Only bind parameters are supported.
The SQL to execute
The options for the query. See QueryRawOptions for details.
Optional
options: QueryRawOptions | QueryRawOptionsWithType<RAW>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.
object with multiple variables.
Optional
options: SetSessionVariablesOptionsQuery options.
Optional
options: QiListSchemasOptionsUse AbstractQueryInterface#listSchemas instead
We highly recommend using Sequelize#transaction instead. If you really want to use the manual solution, don't forget to commit or rollback your transaction once you are done with it.
Transactions started by this method are not automatically passed to queries. You must pass the transaction object manually, even if the Sequelize "disableClsTransactions" option is false.
Optional
options: TransactionOptionstry {
const transaction = await sequelize.startUnmanagedTransaction();
const user = await User.findOne(..., { transaction });
await user.update(..., { transaction });
await transaction.commit();
} catch(err) {
await transaction.rollback();
}
Start a managed transaction: Sequelize will create a transaction, pass it to your callback, and commit it once the promise returned by your callback resolved, or execute a rollback if the promise rejects.
try {
await sequelize.transaction(() => {
const user = await User.findOne(...);
await user.update(...);
});
// By now, the transaction has been committed
} catch {
// If the transaction callback threw an error, the transaction has been rolled back
}
By default, Sequelize uses AsyncLocalStorage to automatically pass the transaction to all queries executed inside the callback (unless you already pass one or set the transaction
option to null).
This can be disabled by setting the Sequelize "disableClsTransactions" option to true. You will then need to pass transactions to your queries manually.
const sequelize = new Sequelize({
// ...
disableClsTransactions: true,
})
await sequelize.transaction(transaction => {
// transactions are not automatically passed around anymore, you need to do it yourself:
const user = await User.findOne(..., { transaction });
await user.update(..., { transaction });
});
If you want to manage your transaction yourself, use startUnmanagedTransaction.
Async callback during which the transaction will be active
Transaction Options
Async callback during which the transaction will be active
Truncate all models registered in this instance. This is done by calling Model.truncate on each model.
Optional
options: SequelizeTruncateOptionsThe options passed to Model.truncate, plus "withoutForeignKeyChecks".
Optional
options: QueryOptionsValidate a value against a field specification
The value to validate
The DataType to validate against
This is the main class, the entry point to sequelize. To use it, you just need to import 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.