Documentation
    Preparing search index...

    Class Sequelize<Dialect>

    This is the main class, the entry point to sequelize. To use it, you just need to import sequelize:

    import { Sequelize } from '@sequelize/core';
    

    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.

    Type Parameters

    Hierarchy (View Summary)

    Index
    addHook: LegacyAddAnyHookFunction<
        SequelizeHooks<AbstractDialect<object, object>>,
    >
    afterAssociate: LegacyAddHookFunction<
        (
            data: AfterAssociateEventData,
            options: AssociationOptions<any>,
        ) => AsyncHookReturn,
    >
    afterBulkCreate: LegacyAddHookFunction<
        (
            instances: readonly Model<any, any>[],
            options: BulkCreateOptions<any>,
        ) => AsyncHookReturn,
    >
    afterBulkDestroy: LegacyAddHookFunction<
        (options: DestroyOptions<any>) => AsyncHookReturn,
    >
    afterBulkRestore: LegacyAddHookFunction<
        (options: RestoreOptions<any>) => AsyncHookReturn,
    >
    afterBulkSync: LegacyAddHookFunction<(options: SyncOptions) => AsyncHookReturn>
    afterBulkUpdate: LegacyAddHookFunction<
        (options: UpdateOptions<any>) => AsyncHookReturn,
    >
    afterConnect: LegacyAddHookFunction<
        (connection: AbstractConnection, config: object) => AsyncHookReturn,
    >
    afterCreate: LegacyAddHookFunction<
        (
            attributes: Model<any, any>,
            options: CreateOptions<any>,
        ) => AsyncHookReturn,
    >
    afterDefine: LegacyAddHookFunction<(model: ModelStatic) => void>
    afterDestroy: LegacyAddHookFunction<
        (
            instance: Model<any, any>,
            options: InstanceDestroyOptions,
        ) => AsyncHookReturn,
    >
    afterDisconnect: LegacyAddHookFunction<(connection: unknown) => AsyncHookReturn>
    afterFind: LegacyAddHookFunction<
        (
            instancesOrInstance:
                | Model<any, any>
                | readonly Model<any, any>[]
                | null,
            options: FindOptions<any>,
        ) => AsyncHookReturn,
    >
    afterPoolAcquire: LegacyAddHookFunction<
        (
            connection: AbstractConnection,
            options?: AcquireConnectionOptions,
        ) => AsyncHookReturn,
    >
    afterQuery: LegacyAddHookFunction<
        (options: QueryOptions, query: AbstractQuery) => AsyncHookReturn,
    >
    afterRestore: LegacyAddHookFunction<
        (
            instance: Model<any, any>,
            options: InstanceRestoreOptions,
        ) => AsyncHookReturn,
    >
    afterSave: LegacyAddHookFunction<
        (
            instance: Model<any, any>,
            options: CreateOptions<any> | InstanceUpdateOptions<any>,
        ) => AsyncHookReturn,
    >
    afterUpdate: LegacyAddHookFunction<
        (
            instance: Model<any, any>,
            options: InstanceUpdateOptions<any>,
        ) => AsyncHookReturn,
    >
    afterUpsert: LegacyAddHookFunction<
        (
            attributes: [Model<any, any>, boolean | null],
            options: UpsertOptions<any>,
        ) => AsyncHookReturn,
    >
    afterValidate: LegacyAddHookFunction<
        (
            instance: Model<any, any>,
            options: ValidationOptions,
        ) => AsyncHookReturn,
    >
    beforeAssociate: LegacyAddHookFunction<
        (
            data: BeforeAssociateEventData,
            options: AssociationOptions<any>,
        ) => AsyncHookReturn,
    >
    beforeBulkCreate: LegacyAddHookFunction<
        (
            instances: Model<any, any>[],
            options: BulkCreateOptions<any>,
        ) => AsyncHookReturn,
    >
    beforeBulkDestroy: LegacyAddHookFunction<
        (options: DestroyOptions<any>) => AsyncHookReturn,
    >
    beforeBulkRestore: LegacyAddHookFunction<
        (options: RestoreOptions<any>) => AsyncHookReturn,
    >
    beforeBulkSync: LegacyAddHookFunction<(options: SyncOptions) => AsyncHookReturn>
    beforeBulkUpdate: LegacyAddHookFunction<
        (options: UpdateOptions<any>) => AsyncHookReturn,
    >
    beforeConnect: LegacyAddHookFunction<(config: object) => AsyncHookReturn>
    beforeCount: LegacyAddHookFunction<
        (options: WritableObjectDeep<CountOptions<any>>) => AsyncHookReturn,
    >
    beforeCreate: LegacyAddHookFunction<
        (
            attributes: Model<any, any>,
            options: CreateOptions<any>,
        ) => AsyncHookReturn,
    >
    beforeDefine: LegacyAddHookFunction<
        (attributes: ModelAttributes<any>, options: ModelOptions) => void,
    >
    beforeDestroy: LegacyAddHookFunction<
        (
            instance: Model<any, any>,
            options: InstanceDestroyOptions,
        ) => AsyncHookReturn,
    >
    beforeDisconnect: LegacyAddHookFunction<
        (connection: AbstractConnection) => AsyncHookReturn,
    >
    beforeFind: LegacyAddHookFunction<
        (options: WritableObjectDeep<FindOptions<any>>) => AsyncHookReturn,
    >
    beforeFindAfterExpandIncludeAll: LegacyAddHookFunction<
        (options: WritableObjectDeep<FindOptions<any>>) => AsyncHookReturn,
    >
    beforeFindAfterOptions: LegacyAddHookFunction<
        (options: WritableObjectDeep<FindOptions<any>>) => AsyncHookReturn,
    >
    beforePoolAcquire: LegacyAddHookFunction<
        (options?: AcquireConnectionOptions) => AsyncHookReturn,
    >
    beforeQuery: LegacyAddHookFunction<
        (options: QueryOptions, query: AbstractQuery) => AsyncHookReturn,
    >
    beforeRestore: LegacyAddHookFunction<
        (
            instance: Model<any, any>,
            options: InstanceRestoreOptions,
        ) => AsyncHookReturn,
    >
    beforeSave: LegacyAddHookFunction<
        (
            instance: Model<any, any>,
            options: CreateOptions<any> | InstanceUpdateOptions<any>,
        ) => AsyncHookReturn,
    >
    beforeUpdate: LegacyAddHookFunction<
        (
            instance: Model<any, any>,
            options: InstanceUpdateOptions<any>,
        ) => AsyncHookReturn,
    >
    beforeUpsert: LegacyAddHookFunction<
        (
            attributes: Model<any, any>,
            options: UpsertOptions<any>,
        ) => AsyncHookReturn,
    >
    beforeValidate: LegacyAddHookFunction<
        (
            instance: Model<any, any>,
            options: ValidationOptions,
        ) => AsyncHookReturn,
    >
    dialect: Dialect
    hasHook: <
        HookName extends keyof SequelizeHooks<AbstractDialect<object, object>>,
    >(
        this: {
            hooks: HookHandler<SequelizeHooks<AbstractDialect<object, object>>>;
        },
        hookName: HookName,
    ) => boolean
    hasHooks: <
        HookName extends keyof SequelizeHooks<AbstractDialect<object, object>>,
    >(
        this: {
            hooks: HookHandler<SequelizeHooks<AbstractDialect<object, object>>>;
        },
        hookName: HookName,
    ) => boolean
    rawOptions: Options<Dialect>

    The 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.

    removeHook: <
        HookName extends keyof SequelizeHooks<AbstractDialect<object, object>>,
    >(
        this: {
            hooks: HookHandler<SequelizeHooks<AbstractDialect<object, object>>>;
        },
        hookName: HookName,
        listenerNameOrListener:
            | string
            | SequelizeHooks<AbstractDialect<object, object>>[HookName],
    ) => void
    runHooks: LegacyRunHookFunction<
        SequelizeHooks<AbstractDialect<object, object>>,
        void,
    >
    Sequelize: typeof Sequelize

    A reference to Sequelize constructor from sequelize. Useful for accessing DataTypes, Errors etc.

    validationFailed: LegacyAddHookFunction<
        (
            instance: Model<any, any>,
            options: ValidationOptions,
            error: unknown,
        ) => AsyncHookReturn,
    >
    afterInit: LegacyAddHookFunction<(sequelize: Sequelize) => void>
    beforeInit: LegacyAddHookFunction<
        (options: Options<AbstractDialect<object, object>>) => void,
    >
    hasHook: <HookName extends keyof StaticSequelizeHooks>(
        this: { hooks: HookHandler<StaticSequelizeHooks> },
        hookName: HookName,
    ) => boolean
    hasHooks: <HookName extends keyof StaticSequelizeHooks>(
        this: { hooks: HookHandler<StaticSequelizeHooks> },
        hookName: HookName,
    ) => boolean
    removeHook: <HookName extends keyof StaticSequelizeHooks>(
        this: { hooks: HookHandler<StaticSequelizeHooks> },
        hookName: HookName,
        listenerNameOrListener: string | StaticSequelizeHooks[HookName],
    ) => void
    • get connectionManager(): never

      Returns never

    • get modelManager(): never

      Returns never

    • get queryGenerator(): Dialect["queryGenerator"]

      The QueryGenerator instance, dialect dependant.

      Returns Dialect["queryGenerator"]

    • get queryInterface(): Dialect["queryInterface"]

      The QueryInterface instance, dialect dependant.

      Returns Dialect["queryInterface"]

    • get version(): string

      Returns the installed version of Sequelize

      Returns string

    • Test the connection by trying to authenticate

      Parameters

      • Optionaloptions: QueryOptions

        Query Options for authentication

      Returns Promise<void>

    • 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.

      Returns Promise<void>

    • Define 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/

      Type Parameters

      Parameters

      • modelName: string

        The name of the model. The model will be stored in sequelize.models under this name

      • Optionalattributes: 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:

      • Optionaloptions: ModelOptions<M>

        These options are merged with the default define options provided to the Sequelize constructor

      Returns ModelStatic<M>

    • 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).

      Parameters

      Returns Promise<void>

    • Drop all tables defined through this sequelize instance. This is done by calling Model.drop on each model

      Parameters

      • Optionaloptions: DropOptions

        The options passed to each call to Model.drop

      Returns Promise<unknown[]>

    • Returns 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.

      Returns Transaction | undefined

    • Returns the database name.

      Returns string

    • 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.

      Returns string

      current version of the dialect that is internally loaded

    • Returns the specified dialect.

      Returns string

    • Returns the dialect-dependant QueryInterface instance.

      Returns Dialect["queryInterface"]

    • Checks whether a model with the given name is defined

      Parameters

      • modelName: string

        The name of a model defined with Sequelize.define

      Returns boolean

      use Sequelize#models instead.

    • Parameters

      • ...values: unknown[]

      Returns void

    • Fetch a Model which is already defined

      Type Parameters

      Parameters

      • modelName: string

        The name of a model defined with Sequelize.define

      Returns ModelStatic<M>

      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

      Parameters

      Returns Promise<[undefined, number]>

    • 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

      Parameters

      Returns Promise<number>

    • 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

      Parameters

      Returns Promise<[number, number]>

    • 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

      Parameters

      Returns Promise<number>

    • 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

      Parameters

      Returns Promise<number>

    • 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

      Parameters

      Returns Promise<ColumnsDescription>

    • 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

      Parameters

      Returns Promise<RawConstraintDescription[]>

    • 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

      Type Parameters

      • M extends Model<any, any>

      Parameters

      Returns Promise<M | null>

    • 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

      Type Parameters

      • M extends Model<any, any>

      Parameters

      Returns Promise<M[]>

    • 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

      Type Parameters

      • T extends object

      Parameters

      Returns Promise<T | null>

    • 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

      Type Parameters

      • T extends object

      Parameters

      Returns Promise<T[]>

    • 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

      Parameters

      Returns Promise<{ [key: string]: unknown } | null>

    • 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

      Parameters

      Returns Promise<[unknown[], unknown]>

    • Get the fn for random based on the dialect

      Returns Fn

    • Parameters

      • version: string

      Returns void

    • 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.

      Parameters

      Returns Promise<unknown>

    • 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.

      Parameters

      Returns Promise<Transaction>

      try {
      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.

      Type Parameters

      • T

      Parameters

      Returns Promise<T>

    • Type Parameters

      • T

      Parameters

      Returns Promise<T>

    • Validate a value against a field specification

      Parameters

      • value: unknown

        The value to validate

      • type: DataType

        The DataType to validate against

      Returns void