Options
All
  • Public
  • Public/Protected
  • All
Menu

Class Sequelize

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

const { Sequelize } = require('@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.

Hierarchy

  • Hooks
    • Sequelize

Index

Constructors

  • 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 uri (see below)
    const sequelize = new Sequelize('mysql://localhost:3306/database', {})

    Parameters

    • database: string

      The name of the database

    • username: string

      The username which is used to authenticate against the database.

    • Optional password: string

      The password which is used to authenticate against the database.

    • Optional options: Options

      An object with options.

    Returns Sequelize

  • Parameters

    • database: string
    • username: string
    • Optional options: Options

    Returns Sequelize

  • Parameters

    Returns Sequelize

  • Instantiate sequelize with an URI

    Parameters

    • uri: string

      A full database URI

    • Optional options: Options

      See above for possible options

    Returns Sequelize

Properties

Sequelize: typeof Sequelize

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

_attributes: any

A similar dummy variable that doesn't exist on the real object. Do not try to access this in real code.

deprecated

This property will become a Symbol in v7 to prevent collisions. Use Attributes instead of this property to be forward-compatible.

_creationAttributes: any

A similar dummy variable that doesn't exist on the real object. Do not try to access this in real code.

deprecated

This property will become a Symbol in v7 to prevent collisions. Use CreationAttributes instead of this property to be forward-compatible.

_model: Model<any, any>

A dummy variable that doesn't exist on the real object. This exists so Typescript can infer the type of the attributes in static functions. Don't try to access this!

and: <T>(...args: T) => { [and]: T }

Type declaration

    • <T>(...args: T): { [and]: T }
    • An AND query

      Type parameters

      • T: any[]

      Parameters

      • Rest ...args: T

        Each argument will be joined by AND

      Returns { [and]: T }

      • [and]: T
cast: (val: unknown, type: string) => Cast

Type declaration

    • (val: unknown, type: string): Cast
    • Creates a object representing a call to the cast function.

      Parameters

      • val: unknown

        The value to cast

      • type: string

        The type to cast it to

      Returns Cast

col: (col: string) => Col

Type declaration

    • (col: string): Col
    • Creates a object representing a column in the DB. This is often useful in conjunction with sequelize.fn, since raw string arguments to fn will be escaped.

      Parameters

      • col: string

        The name of the column

      Returns Col

config: Config

Final config that is used by sequelize.

connectionManager: ConnectionManager
dialect: AbstractDialect
fn: (fn: string, ...args: any) => Fn

Type declaration

    • (fn: string, ...args: any): Fn
    • Creates a 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.update({
      username: self.sequelize.fn('upper', self.sequelize.col('username'))
      })

      Parameters

      • fn: string

        The function you want to call

      • Rest ...args: any

        All further arguments will be passed as arguments to the function

      Returns Fn

json: (conditionsOrPath: string | object, value?: string | number | boolean) => Json

Type declaration

    • (conditionsOrPath: string | object, value?: string | number | boolean): Json
    • Creates an object representing nested where conditions for postgres's json data-type.

      Parameters

      • conditionsOrPath: string | object

        A hash containing strings/numbers or other nested hash, a string using dot notation or a string using postgres json syntax.

      • Optional value: string | number | boolean

        An optional value to compare against. Produces a string of the form "<json path> = '<value>'".

      Returns Json

literal: (val: string) => Literal

Type declaration

    • Creates a object representing a literal, i.e. something that will not be escaped.

      Parameters

      • val: string

      Returns Literal

modelManager: ModelManager
models: {}

Dictionary of all models linked with this instance.

Type declaration

options: PartlyRequired<Options, "transactionType" | "isolationLevel">
or: <T>(...args: T) => { [or]: T }

Type declaration

    • <T>(...args: T): { [or]: T }
    • An OR query

      Type parameters

      • T: any[]

      Parameters

      • Rest ...args: T

        Each argument will be joined by OR

      Returns { [or]: T }

      • [or]: T
where: { <Op>(leftOperand: Where<typeof eq> | WhereLeftOperand, operator: Op, rightOperand: WhereOperators<any>[Op]): Where; <Op>(leftOperand: any, operator: string, rightOperand: any): Where; (leftOperand: WhereLeftOperand, rightOperand: any): Where }

Type declaration

    • A way of specifying "attr = condition". Can be used as a replacement for the POJO syntax (e.g. where: { name: 'Lily' }) when you need to compare a column that the POJO syntax cannot represent.

      example

      // Using an attribute as the left operand. // Equal to: WHERE first_name = 'Lily' where(User.rawAttributes.firstName, Op.eq, 'Lily');

      example

      // Using a column name as the left operand. // Equal to: WHERE first_name = 'Lily' where(col('first_name'), Op.eq, 'Lily');

      example

      // Using a SQL function on the left operand. // Equal to: WHERE LOWER(first_name) = 'lily' where(fn('LOWER', col('first_name')), Op.eq, 'lily');

      example

      // Using raw SQL as the left operand. // Equal to: WHERE 'Lily' = 'Lily' where(literal('Lily'), Op.eq, 'Lily');

      Type parameters

      Parameters

      • leftOperand: Where<typeof eq> | WhereLeftOperand

        The left side of the comparison.

        • A value taken from YourModel.rawAttributes, to reference an attribute. The attribute must be defined in your model definition.
        • A Literal (using {@link Sequelize#literal})
        • A SQL Function (using {@link Sequelize#fn})
        • A Column name (using {@link Sequelize#col}) Note that simple strings to reference an attribute are not supported. You can use the POJO syntax instead.
      • operator: Op

        The comparison operator to use. If unspecified, defaults to {@link Op.eq}.

      • rightOperand: WhereOperators<any>[Op]

        The right side of the comparison. Its value depends on the used operator. See WhereOperators for information about what value is valid for each operator.

      Returns Where

    • Type parameters

      Parameters

      • leftOperand: any
      • operator: string
      • rightOperand: any

      Returns Where

    • Parameters

      Returns Where

DataTypes: DataTypes
Op: OpTypes

For internal use only.

and: <T>(...args: T) => { [and]: T }

Type declaration

    • <T>(...args: T): { [and]: T }
    • An AND query

      Type parameters

      • T: any[]

      Parameters

      • Rest ...args: T

        Each argument will be joined by AND

      Returns { [and]: T }

      • [and]: T
cast: (val: unknown, type: string) => Cast

Type declaration

    • (val: unknown, type: string): Cast
    • Creates a object representing a call to the cast function.

      Parameters

      • val: unknown

        The value to cast

      • type: string

        The type to cast it to

      Returns Cast

col: (col: string) => Col

Type declaration

    • (col: string): Col
    • Creates a object representing a column in the DB. This is often useful in conjunction with sequelize.fn, since raw string arguments to fn will be escaped.

      Parameters

      • col: string

        The name of the column

      Returns Col

fn: (fn: string, ...args: any) => Fn

Type declaration

    • (fn: string, ...args: any): Fn
    • Creates a 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.update({
      username: self.sequelize.fn('upper', self.sequelize.col('username'))
      })

      Parameters

      • fn: string

        The function you want to call

      • Rest ...args: any

        All further arguments will be passed as arguments to the function

      Returns Fn

json: (conditionsOrPath: string | object, value?: string | number | boolean) => Json

Type declaration

    • (conditionsOrPath: string | object, value?: string | number | boolean): Json
    • Creates an object representing nested where conditions for postgres's json data-type.

      Parameters

      • conditionsOrPath: string | object

        A hash containing strings/numbers or other nested hash, a string using dot notation or a string using postgres json syntax.

      • Optional value: string | number | boolean

        An optional value to compare against. Produces a string of the form "<json path> = '<value>'".

      Returns Json

literal: (val: string) => Literal

Type declaration

    • Creates a object representing a literal, i.e. something that will not be escaped.

      Parameters

      • val: string

      Returns Literal

or: <T>(...args: T) => { [or]: T }

Type declaration

    • <T>(...args: T): { [or]: T }
    • An OR query

      Type parameters

      • T: any[]

      Parameters

      • Rest ...args: T

        Each argument will be joined by OR

      Returns { [or]: T }

      • [or]: T
where: { <Op>(leftOperand: Where<typeof eq> | WhereLeftOperand, operator: Op, rightOperand: WhereOperators<any>[Op]): Where; <Op>(leftOperand: any, operator: string, rightOperand: any): Where; (leftOperand: WhereLeftOperand, rightOperand: any): Where }

Type declaration

    • A way of specifying "attr = condition". Can be used as a replacement for the POJO syntax (e.g. where: { name: 'Lily' }) when you need to compare a column that the POJO syntax cannot represent.

      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.

      example

      // Using an attribute as the left operand. // Equal to: WHERE first_name = 'Lily' where(User.rawAttributes.firstName, Op.eq, 'Lily');

      example

      // Using a column name as the left operand. // Equal to: WHERE first_name = 'Lily' where(col('first_name'), Op.eq, 'Lily');

      example

      // Using a SQL function on the left operand. // Equal to: WHERE LOWER(first_name) = 'lily' where(fn('LOWER', col('first_name')), Op.eq, 'lily');

      example

      // Using raw SQL as the left operand. // Equal to: WHERE 'Lily' = 'Lily' where(literal('Lily'), Op.eq, 'Lily');

      Type parameters

      Parameters

      • leftOperand: Where<typeof eq> | WhereLeftOperand

        The left side of the comparison.

        • A value taken from YourModel.rawAttributes, to reference an attribute. The attribute must be defined in your model definition.
        • A Literal (using {@link Sequelize#literal})
        • A SQL Function (using {@link Sequelize#fn})
        • A Column name (using {@link Sequelize#col}) Note that simple strings to reference an attribute are not supported. You can use the POJO syntax instead.
      • operator: Op

        The comparison operator to use. If unspecified, defaults to {@link Op.eq}.

      • rightOperand: WhereOperators<any>[Op]

        The right side of the comparison. Its value depends on the used operator. See WhereOperators for information about what value is valid for each operator.

      Returns Where

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

      Type parameters

      Parameters

      • leftOperand: any
      • operator: string
      • rightOperand: any

      Returns Where

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

      Parameters

      Returns Where

Accessors

  • get version(): string
  • Returns the installed version of Sequelize

    Returns string

Methods

  • addHook<K>(hookType: K, name: string, fn: SequelizeHooks<Model<any, any>, any, any>[K]): Sequelize
  • addHook<K>(hookType: K, fn: SequelizeHooks<Model<any, any>, any, any>[K]): Sequelize
  • Add a hook to the model

    Type parameters

    • K: keyof SequelizeHooks<M, TModelAttributes, TCreationAttributes>

    Parameters

    • hookType: K
    • name: string

      Provide a name for the hook function. It can be used to remove the hook later or to order hooks based on some sort of priority system in the future.

    • fn: SequelizeHooks<Model<any, any>, any, any>[K]

    Returns Sequelize

  • Type parameters

    • K: keyof SequelizeHooks<M, TModelAttributes, TCreationAttributes>

    Parameters

    • hookType: K
    • fn: SequelizeHooks<Model<any, any>, any, any>[K]

    Returns Sequelize

  • A hook that is run after creating instances in bulk

    Parameters

    Returns void

  • Parameters

    Returns void

  • afterBulkDestroy(name: string, fn: (options: DestroyOptions<any>) => void): void
  • afterBulkDestroy(fn: (options: DestroyOptions<any>) => void): void
  • A hook that is run after destroying instances in bulk

    Parameters

    Returns void

  • Parameters

    Returns void

  • afterBulkSync(name: string, fn: (options: SyncOptions) => HookReturn): void
  • afterBulkSync(fn: (options: SyncOptions) => HookReturn): void
  • A hook that is run after sequelize.sync call

    Parameters

    • name: string
    • fn: (options: SyncOptions) => HookReturn

      A callback function that is called with options passed to sequelize.sync

    Returns void

  • Parameters

    Returns void

  • afterBulkUpdate(name: string, fn: (options: UpdateOptions<any>) => void): void
  • afterBulkUpdate(fn: (options: UpdateOptions<any>) => void): void
  • A hook that is run after updating instances in bulk

    Parameters

    Returns void

  • Parameters

    Returns void

  • afterCreate(name: string, fn: (attributes: Model<any, any>, options: CreateOptions<any>) => void): void
  • afterCreate(fn: (attributes: Model<any, any>, options: CreateOptions<any>) => void): void
  • A hook that is run after creating a single instance

    Parameters

    • name: string
    • fn: (attributes: Model<any, any>, options: CreateOptions<any>) => void

      A callback function that is called with attributes, options

    Returns void

  • Parameters

    Returns void

  • A hook that is run after a define call

    Parameters

    Returns void

  • Parameters

    Returns void

  • afterFind(name: string, fn: (instancesOrInstance: null | Model<any, any> | Model<any, any>[], options: FindOptions<any>) => void): void
  • afterFind(fn: (instancesOrInstance: null | Model<any, any> | Model<any, any>[], options: FindOptions<any>) => void): void
  • A hook that is run after a find (select) query

    Parameters

    • name: string
    • fn: (instancesOrInstance: null | Model<any, any> | Model<any, any>[], options: FindOptions<any>) => void

      A callback function that is called with instance(s), options

    Returns void

  • Parameters

    Returns void

  • afterInit(name: string, fn: (sequelize: Sequelize) => void): void
  • afterInit(fn: (sequelize: Sequelize) => void): void
  • A hook that is run after Sequelize() call

    Parameters

    • name: string
    • fn: (sequelize: Sequelize) => void

      A callback function that is called with sequelize

    Returns void

  • Parameters

    Returns void

  • afterSync(name: string, fn: (options: SyncOptions) => HookReturn): void
  • afterSync(fn: (options: SyncOptions) => HookReturn): void
  • A hook that is run after Model.sync call

    Parameters

    • name: string
    • fn: (options: SyncOptions) => HookReturn

      A callback function that is called with options passed to Model.sync

    Returns void

  • Parameters

    Returns void

  • afterUpdate(name: string, fn: (instance: Model<any, any>, options: UpdateOptions<any>) => void): void
  • afterUpdate(fn: (instance: Model<any, any>, options: UpdateOptions<any>) => void): void
  • A hook that is run after updating a single instance

    Parameters

    • name: string
    • fn: (instance: Model<any, any>, options: UpdateOptions<any>) => void

      A callback function that is called with instance, options

    Returns void

  • Parameters

    Returns void

  • afterValidate(name: string, fn: (instance: Model<any, any>, options: ValidationOptions) => void): void
  • afterValidate(fn: (instance: Model<any, any>, options: ValidationOptions) => void): void
  • A hook that is run after validation

    Parameters

    • name: string
    • fn: (instance: Model<any, any>, options: ValidationOptions) => void

      A callback function that is called with instance, options

        • (instance: Model<any, any>, options: ValidationOptions): void
        • Parameters

          • instance: Model<any, any>
          • options: ValidationOptions

          Returns void

    Returns void

  • Parameters

    • fn: (instance: Model<any, any>, options: ValidationOptions) => void
        • (instance: Model<any, any>, options: ValidationOptions): void
        • Parameters

          • instance: Model<any, any>
          • options: ValidationOptions

          Returns void

    Returns void

  • Test the connection by trying to authenticate

    Parameters

    • Optional options: QueryOptions

      Query Options for authentication

    Returns Promise<void>

  • A hook that is run before creating instances in bulk

    Parameters

    Returns void

  • Parameters

    Returns void

  • beforeBulkSync(name: string, fn: (options: SyncOptions) => HookReturn): void
  • beforeBulkSync(fn: (options: SyncOptions) => HookReturn): void
  • A hook that is run before sequelize.sync call

    Parameters

    • name: string
    • fn: (options: SyncOptions) => HookReturn

      A callback function that is called with options passed to sequelize.sync

    Returns void

  • Parameters

    Returns void

  • beforeBulkUpdate(name: string, fn: (options: UpdateOptions<any>) => void): void
  • beforeBulkUpdate(fn: (options: UpdateOptions<any>) => void): void
  • A hook that is run after updating instances in bulk

    Parameters

    Returns void

  • Parameters

    Returns void

  • beforeCreate(name: string, fn: (attributes: Model<any, any>, options: CreateOptions<any>) => void): void
  • beforeCreate(fn: (attributes: Model<any, any>, options: CreateOptions<any>) => void): void
  • A hook that is run before creating a single instance

    Parameters

    • name: string
    • fn: (attributes: Model<any, any>, options: CreateOptions<any>) => void

      A callback function that is called with attributes, options

    Returns void

  • Parameters

    Returns void

  • beforeFind(name: string, fn: (options: FindOptions<any>) => void): void
  • beforeFind(fn: (options: FindOptions<any>) => void): void
  • A hook that is run before a find (select) query

    Parameters

    • name: string
    • fn: (options: FindOptions<any>) => void

      A callback function that is called with options

    Returns void

  • Parameters

    Returns void

  • beforeFindAfterExpandIncludeAll(name: string, fn: (options: FindOptions<any>) => void): void
  • beforeFindAfterExpandIncludeAll(fn: (options: FindOptions<any>) => void): void
  • A hook that is run before a find (select) query, after any { include: {all: ...} } options are expanded

    Parameters

    • name: string
    • fn: (options: FindOptions<any>) => void

      A callback function that is called with options

    Returns void

  • Parameters

    Returns void

  • beforeFindAfterOptions(name: string, fn: (options: FindOptions<any>) => void): void
  • beforeFindAfterOptions(fn: (options: FindOptions<any>) => void): void
  • A hook that is run before a find (select) query, after all option parsing is complete

    Parameters

    • name: string
    • fn: (options: FindOptions<any>) => void

      A callback function that is called with options

    Returns void

  • Parameters

    Returns void

  • beforeInit(name: string, fn: (config: Config, options: Options) => void): void
  • beforeInit(fn: (config: Config, options: Options) => void): void
  • A hook that is run before Sequelize() call

    Parameters

    • name: string
    • fn: (config: Config, options: Options) => void

      A callback function that is called with config, options

    Returns void

  • Parameters

    Returns void

  • beforeSync(name: string, fn: (options: SyncOptions) => HookReturn): void
  • beforeSync(fn: (options: SyncOptions) => HookReturn): void
  • A hook that is run before Model.sync call

    Parameters

    • name: string
    • fn: (options: SyncOptions) => HookReturn

      A callback function that is called with options passed to Model.sync

    Returns void

  • Parameters

    Returns void

  • beforeUpdate(name: string, fn: (instance: Model<any, any>, options: UpdateOptions<any>) => void): void
  • beforeUpdate(fn: (instance: Model<any, any>, options: UpdateOptions<any>) => void): void
  • A hook that is run before updating a single instance

    Parameters

    • name: string
    • fn: (instance: Model<any, any>, options: UpdateOptions<any>) => void

      A callback function that is called with instance, options

    Returns void

  • Parameters

    Returns void

  • beforeValidate(name: string, fn: (instance: Model<any, any>, options: ValidationOptions) => void): void
  • beforeValidate(fn: (instance: Model<any, any>, options: ValidationOptions) => void): void
  • A hook that is run before validation

    Parameters

    • name: string
    • fn: (instance: Model<any, any>, options: ValidationOptions) => void

      A callback function that is called with instance, options

        • (instance: Model<any, any>, options: ValidationOptions): void
        • Parameters

          • instance: Model<any, any>
          • options: ValidationOptions

          Returns void

    Returns void

  • Parameters

    • fn: (instance: Model<any, any>, options: ValidationOptions) => void
        • (instance: Model<any, any>, options: ValidationOptions): void
        • Parameters

          • instance: Model<any, any>
          • options: ValidationOptions

          Returns void

    Returns void

  • close(): 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>

  • createSchema(schema: string, options?: Logging): Promise<unknown>
  • 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.

    Parameters

    • schema: string

      Name of the schema

    • Optional options: Logging

      Options supplied

    Returns Promise<unknown>

  • databaseVersion(): Promise<string>
  • Returns the database version

    Returns Promise<string>

  • 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

    • 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

    Returns ModelStatic<M>

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

    Parameters

    • Optional options: DropOptions

      The options passed to each call to Model.drop

    Returns Promise<unknown[]>

  • dropAllSchemas(options?: Logging): Promise<unknown[]>
  • 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.

    Parameters

    • Optional options: Logging

      Options supplied

    Returns Promise<unknown[]>

  • dropSchema(schema: string, options?: Logging): Promise<unknown[]>
  • 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

    Parameters

    • schema: string

      Name of the schema

    • Optional options: Logging

      Options supplied

    Returns Promise<unknown[]>

  • escape(value: string | number | Date): string
  • Escape value.

    Parameters

    • value: string | number | Date

      Value that needs to be escaped

    Returns string

  • getDatabaseName(): string
  • Returns the database name.

    Returns string

  • getDialect(): string
  • Returns the specified dialect.

    Returns string

  • Returns an instance of QueryInterface.

    Returns QueryInterface

  • hasHook<K>(hookType: K): boolean
  • Check whether the mode has any hooks of this type

    Type parameters

    • K: keyof SequelizeHooks<M, TModelAttributes, TCreationAttributes>

    Parameters

    • hookType: K

    Returns boolean

  • hasHooks<K>(hookType: K): boolean
  • Type parameters

    • K: keyof SequelizeHooks<M, TModelAttributes, TCreationAttributes>

    Parameters

    • hookType: K

    Returns boolean

  • isDefined(modelName: string): boolean
  • Checks whether a model with the given name is defined

    Parameters

    • modelName: string

      The name of a model defined with Sequelize.define

    Returns boolean

  • Fetch a Model which is already defined

    Parameters

    • modelName: string

      The name of a model defined with Sequelize.define

    Returns ModelStatic<Model<any, any>>

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

  • Parameters

    Returns Promise<number>

  • Parameters

    Returns Promise<[number, number]>

  • Parameters

    Returns Promise<number>

  • Parameters

    Returns Promise<void>

  • Parameters

    Returns Promise<number>

  • Parameters

    Returns Promise<string[]>

  • Parameters

    Returns Promise<ColumnsDescription>

  • Type parameters

    Parameters

    Returns Promise<null | M>

  • Type parameters

    Parameters

    Returns Promise<M[]>

  • Type parameters

    • T: object

    Parameters

    Returns Promise<null | T>

  • Type parameters

    • T: object

    Parameters

    Returns Promise<T[]>

  • Parameters

    Returns Promise<null | {}>

  • Parameters

    Returns Promise<[unknown[], unknown]>

  • Works like {@link Sequelize#query}, but does not inline replacements. Only bind parameters are supported.

    Parameters

    Returns Promise<[undefined, number]>

  • Parameters

    Returns Promise<number>

  • Parameters

    Returns Promise<[number, number]>

  • Parameters

    Returns Promise<number>

  • Parameters

    Returns Promise<void>

  • Parameters

    Returns Promise<number>

  • Parameters

    Returns Promise<string[]>

  • Parameters

    Returns Promise<ColumnsDescription>

  • Type parameters

    Parameters

    Returns Promise<null | M>

  • Type parameters

    Parameters

    Returns Promise<M[]>

  • Type parameters

    • T: object

    Parameters

    Returns Promise<null | T>

  • Type parameters

    • T: object

    Parameters

    Returns Promise<T[]>

  • Parameters

    Returns Promise<null | {}>

  • Parameters

    Returns Promise<[unknown[], unknown]>

  • random(): Fn
  • Get the fn for random based on the dialect

    Returns Fn

  • removeHook<K>(hookType: K, name: string): Sequelize
  • Remove hook from the model

    Type parameters

    • K: keyof SequelizeHooks<M, TModelAttributes, TCreationAttributes>

    Parameters

    • hookType: K
    • name: string

    Returns Sequelize

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

  • showAllSchemas(options?: Logging): Promise<object[]>
  • 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.

    Parameters

    • Optional options: Logging

      Options supplied

    Returns Promise<object[]>

  • Sync all defined models to the DB.

    Parameters

    Returns Promise<Sequelize>

  • 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

      try {
    const transaction = await sequelize.transaction();
    const user = await User.findOne(..., { transaction });
    await user.update(..., { transaction });
    await transaction.commit();
    } catch(err) {
    await transaction.rollback();
    }
    })

    A syntax for automatically committing or rolling back based on the promise chain resolution is also supported:

    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);
    }

    If you have CLS enabled, the transaction will automatically be passed to any query that runs witin the callback. To enable CLS, add it do your project, create a namespace and set it on the sequelize constructor:

    const cls = require('cls-hooked');
    const namespace = cls.createNamespace('....');
    const Sequelize = require('@sequelize/core');
    Sequelize.useCLS(namespace);

    Note, that CLS is enabled for all sequelize instances, and all instances will share the same namespace

    Type parameters

    • T

    Parameters

    Returns Promise<T>

  • Type parameters

    • T

    Parameters

    Returns Promise<T>

  • Parameters

    Returns Promise<Transaction>

  • Truncate all tables defined through the sequelize models. This is done by calling Model.truncate() on each model.

    Parameters

    Returns Promise<unknown[]>

  • Parameters

    Returns Promise<void>

  • addHook<H, K>(this: HooksStatic<H>, hookType: K, name: string, fn: SequelizeHooks<H["_model"], Attributes<H>, CreationAttributes<H>>[K]): HooksCtor<H>
  • addHook<H, K>(this: HooksStatic<H>, hookType: K, fn: SequelizeHooks<H["_model"], Attributes<H>, CreationAttributes<H>>[K]): HooksCtor<H>
  • Add a hook to the model

    Type parameters

    Parameters

    • this: HooksStatic<H>
    • hookType: K
    • name: string

      Provide a name for the hook function. It can be used to remove the hook later or to order hooks based on some sort of priority system in the future.

    • fn: SequelizeHooks<H["_model"], Attributes<H>, CreationAttributes<H>>[K]

    Returns HooksCtor<H>

  • Type parameters

    Parameters

    Returns HooksCtor<H>

  • A hook that is run after creating instances in bulk

    Parameters

    Returns void

  • Parameters

    Returns void

  • afterBulkDestroy(name: string, fn: (options: DestroyOptions<any>) => void): void
  • afterBulkDestroy(fn: (options: DestroyOptions<any>) => void): void
  • A hook that is run after destroying instances in bulk

    Parameters

    Returns void

  • Parameters

    Returns void

  • afterBulkSync(name: string, fn: (options: SyncOptions) => HookReturn): void
  • afterBulkSync(fn: (options: SyncOptions) => HookReturn): void
  • A hook that is run after sequelize.sync call

    Parameters

    • name: string
    • fn: (options: SyncOptions) => HookReturn

      A callback function that is called with options passed to sequelize.sync

    Returns void

  • Parameters

    Returns void

  • afterBulkUpdate(name: string, fn: (options: UpdateOptions<any>) => void): void
  • afterBulkUpdate(fn: (options: UpdateOptions<any>) => void): void
  • A hook that is run after updating instances in bulk

    Parameters

    Returns void

  • Parameters

    Returns void

  • afterConnect(name: string, fn: (connection: unknown, options: Config) => void): void
  • afterConnect(fn: (connection: unknown, options: Config) => void): void
  • A hook that is run after a connection is established

    Parameters

    • name: string
    • fn: (connection: unknown, options: Config) => void

      A callback function that is called with options

        • (connection: unknown, options: Config): void
        • Parameters

          • connection: unknown
          • options: Config

          Returns void

    Returns void

  • Parameters

    • fn: (connection: unknown, options: Config) => void
        • (connection: unknown, options: Config): void
        • Parameters

          • connection: unknown
          • options: Config

          Returns void

    Returns void

  • afterCreate(name: string, fn: (attributes: Model<any, any>, options: CreateOptions<any>) => void): void
  • afterCreate(fn: (attributes: Model<any, any>, options: CreateOptions<any>) => void): void
  • A hook that is run after creating a single instance

    Parameters

    • name: string
    • fn: (attributes: Model<any, any>, options: CreateOptions<any>) => void

      A callback function that is called with attributes, options

    Returns void

  • Parameters

    Returns void

  • A hook that is run after a define call

    Parameters

    Returns void

  • Parameters

    Returns void

  • afterDisconnect(name: string, fn: (connection: unknown) => void): void
  • afterDisconnect(fn: (connection: unknown) => void): void
  • A hook that is run after a connection is released

    Parameters

    • name: string
    • fn: (connection: unknown) => void

      A callback function that is called with options

        • (connection: unknown): void
        • Parameters

          • connection: unknown

          Returns void

    Returns void

  • Parameters

    • fn: (connection: unknown) => void
        • (connection: unknown): void
        • Parameters

          • connection: unknown

          Returns void

    Returns void

  • afterFind(name: string, fn: (instancesOrInstance: null | Model<any, any> | Model<any, any>[], options: FindOptions<any>) => void): void
  • afterFind(fn: (instancesOrInstance: null | Model<any, any> | Model<any, any>[], options: FindOptions<any>) => void): void
  • A hook that is run after a find (select) query

    Parameters

    • name: string
    • fn: (instancesOrInstance: null | Model<any, any> | Model<any, any>[], options: FindOptions<any>) => void

      A callback function that is called with instance(s), options

    Returns void

  • Parameters

    Returns void

  • afterInit(name: string, fn: (sequelize: Sequelize) => void): void
  • afterInit(fn: (sequelize: Sequelize) => void): void
  • A hook that is run after Sequelize() call

    Parameters

    • name: string
    • fn: (sequelize: Sequelize) => void

      A callback function that is called with sequelize

    Returns void

  • Parameters

    Returns void

  • afterSync(name: string, fn: (options: SyncOptions) => HookReturn): void
  • afterSync(fn: (options: SyncOptions) => HookReturn): void
  • A hook that is run after Model.sync call

    Parameters

    • name: string
    • fn: (options: SyncOptions) => HookReturn

      A callback function that is called with options passed to Model.sync

    Returns void

  • Parameters

    Returns void

  • afterUpdate(name: string, fn: (instance: Model<any, any>, options: UpdateOptions<any>) => void): void
  • afterUpdate(fn: (instance: Model<any, any>, options: UpdateOptions<any>) => void): void
  • A hook that is run after updating a single instance

    Parameters

    • name: string
    • fn: (instance: Model<any, any>, options: UpdateOptions<any>) => void

      A callback function that is called with instance, options

    Returns void

  • Parameters

    Returns void

  • afterValidate(name: string, fn: (instance: Model<any, any>, options: ValidationOptions) => void): void
  • afterValidate(fn: (instance: Model<any, any>, options: ValidationOptions) => void): void
  • A hook that is run after validation

    Parameters

    • name: string
    • fn: (instance: Model<any, any>, options: ValidationOptions) => void

      A callback function that is called with instance, options

        • (instance: Model<any, any>, options: ValidationOptions): void
        • Parameters

          • instance: Model<any, any>
          • options: ValidationOptions

          Returns void

    Returns void

  • Parameters

    • fn: (instance: Model<any, any>, options: ValidationOptions) => void
        • (instance: Model<any, any>, options: ValidationOptions): void
        • Parameters

          • instance: Model<any, any>
          • options: ValidationOptions

          Returns void

    Returns void

  • A hook that is run before creating instances in bulk

    Parameters

    Returns void

  • Parameters

    Returns void

  • beforeBulkSync(dname: string, fn: (options: SyncOptions) => HookReturn): void
  • beforeBulkSync(fn: (options: SyncOptions) => HookReturn): void
  • A hook that is run before sequelize.sync call

    Parameters

    • dname: string
    • fn: (options: SyncOptions) => HookReturn

      A callback function that is called with options passed to sequelize.sync

    Returns void

  • Parameters

    Returns void

  • beforeBulkUpdate(name: string, fn: (options: UpdateOptions<any>) => void): void
  • beforeBulkUpdate(fn: (options: UpdateOptions<any>) => void): void
  • A hook that is run after updating instances in bulk

    Parameters

    Returns void

  • Parameters

    Returns void

  • beforeCreate(name: string, fn: (attributes: Model<any, any>, options: CreateOptions<any>) => void): void
  • beforeCreate(fn: (attributes: Model<any, any>, options: CreateOptions<any>) => void): void
  • A hook that is run before creating a single instance

    Parameters

    • name: string
    • fn: (attributes: Model<any, any>, options: CreateOptions<any>) => void

      A callback function that is called with attributes, options

    Returns void

  • Parameters

    Returns void

  • beforeDisconnect(name: string, fn: (connection: unknown) => void): void
  • beforeDisconnect(fn: (connection: unknown) => void): void
  • A hook that is run before a connection is released

    Parameters

    • name: string
    • fn: (connection: unknown) => void

      A callback function that is called with options

        • (connection: unknown): void
        • Parameters

          • connection: unknown

          Returns void

    Returns void

  • Parameters

    • fn: (connection: unknown) => void
        • (connection: unknown): void
        • Parameters

          • connection: unknown

          Returns void

    Returns void

  • beforeFind(name: string, fn: (options: FindOptions<any>) => void): void
  • beforeFind(fn: (options: FindOptions<any>) => void): void
  • A hook that is run before a find (select) query

    Parameters

    • name: string
    • fn: (options: FindOptions<any>) => void

      A callback function that is called with options

    Returns void

  • Parameters

    Returns void

  • beforeFindAfterExpandIncludeAll(name: string, fn: (options: FindOptions<any>) => void): void
  • beforeFindAfterExpandIncludeAll(fn: (options: FindOptions<any>) => void): void
  • A hook that is run before a find (select) query, after any { include: {all: ...} } options are expanded

    Parameters

    • name: string
    • fn: (options: FindOptions<any>) => void

      A callback function that is called with options

    Returns void

  • Parameters

    Returns void

  • beforeFindAfterOptions(name: string, fn: (options: FindOptions<any>) => void): void
  • beforeFindAfterOptions(fn: (options: FindOptions<any>) => void): void
  • A hook that is run before a find (select) query, after all option parsing is complete

    Parameters

    • name: string
    • fn: (options: FindOptions<any>) => void

      A callback function that is called with options

    Returns void

  • Parameters

    Returns void

  • beforeInit(name: string, fn: (config: Config, options: Options) => void): void
  • beforeInit(fn: (config: Config, options: Options) => void): void
  • A hook that is run before Sequelize() call

    Parameters

    • name: string
    • fn: (config: Config, options: Options) => void

      A callback function that is called with config, options

    Returns void

  • Parameters

    Returns void

  • beforeSync(name: string, fn: (options: SyncOptions) => HookReturn): void
  • beforeSync(fn: (options: SyncOptions) => HookReturn): void
  • A hook that is run before Model.sync call

    Parameters

    • name: string
    • fn: (options: SyncOptions) => HookReturn

      A callback function that is called with options passed to Model.sync

    Returns void

  • Parameters

    Returns void

  • beforeUpdate(name: string, fn: (instance: Model<any, any>, options: UpdateOptions<any>) => void): void
  • beforeUpdate(fn: (instance: Model<any, any>, options: UpdateOptions<any>) => void): void
  • A hook that is run before updating a single instance

    Parameters

    • name: string
    • fn: (instance: Model<any, any>, options: UpdateOptions<any>) => void

      A callback function that is called with instance, options

    Returns void

  • Parameters

    Returns void

  • beforeValidate(name: string, fn: (instance: Model<any, any>, options: ValidationOptions) => void): void
  • beforeValidate(fn: (instance: Model<any, any>, options: ValidationOptions) => void): void
  • A hook that is run before validation

    Parameters

    • name: string
    • fn: (instance: Model<any, any>, options: ValidationOptions) => void

      A callback function that is called with instance, options

        • (instance: Model<any, any>, options: ValidationOptions): void
        • Parameters

          • instance: Model<any, any>
          • options: ValidationOptions

          Returns void

    Returns void

  • Parameters

    • fn: (instance: Model<any, any>, options: ValidationOptions) => void
        • (instance: Model<any, any>, options: ValidationOptions): void
        • Parameters

          • instance: Model<any, any>
          • options: ValidationOptions

          Returns void

    Returns void

  • Check whether the mode has any hooks of this type

    Type parameters

    • H: Hooks<Model<any, any>, any, any, H>

    Parameters

    Returns boolean

  • Type parameters

    • H: Hooks<Model<any, any>, any, any, H>

    Parameters

    Returns boolean

  • removeHook<H>(this: HooksStatic<H>, hookType: keyof SequelizeHooks<H["_model"], Attributes<H>, CreationAttributes<H>>, name: string): HooksCtor<H>
  • Remove hook from the model

    Type parameters

    • H: Hooks<Model<any, any>, any, any, H>

    Parameters

    Returns HooksCtor<H>

  • Use CLS with Sequelize. CLS namespace provided is stored as Sequelize._cls and Promise is patched to use the namespace, using cls-hooked module.

    Parameters

    Returns typeof Sequelize

Generated using TypeDoc